** This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details **

Question: Can someone tell me the advantages of using synchronized methods instead of synchronized code blocks? It’s best to give an example

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — the following for the answer, according to support sorting votes — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Answer 1 (votes for 442) :
Can anyone tell me the advantage of the synchronized method over the synchronized block with an example? Thanks.
Copy the code

There is no obvious advantage to using synchronized methods to replace synchronized code blocks. Perhaps one thing (but I don’t think it’s an advantage) is that you don’t need to add an object reference to this. Synchronization method:

public synchronized void method() { // blocks "this" from here.... . . . }// to here
Copy the code

Sync code block:

public void method() { 
    synchronized( this ) { // blocks "this" from here .... . . . }// to here...
}
Copy the code

See? There is no advantage at all.

However, blocks do have an advantage over methods, mainly in terms of flexibility, because you can use another object as a lock, and synchronizing that method locks the entire object. Compare the following two pieces of code:

// Lock the entire object. private synchronizedvoid someInputRelatedWork(){... } private synchronizedvoid someOutputRelatedWork(){... }Copy the code
// Use the specified object lock
Object inputLock = new Object(a);Object outputLock = new Object(a); privatevoid someInputRelatedWork() {
    synchronized(inputLock){... } } privatevoid someOutputRelatedWork() {
    synchronized(outputLock){... }}Copy the code

Also, if the extension method can still keep part of the lock synchronized:

 private void method(){... code here ... code here ... code heresynchronized( lock ){... very few linesof code here
    }
     ... code here
     ... code here
     ... code here
     ... code here
}
Copy the code
Answer 2 (votes for 142) :

The only difference is that the synchronized code block can choose to specify an object as the lock, whereas the synchronized method can only use this(or its corresponding class instance). For example, the following two semantics are equivalent:

synchronized void foo(){... }void foo() {
    synchronized (this) {... }}Copy the code

The latter is more flexible because it can compete for an associated lock on any object (usually a member variable). It is also more refined because you can execute concurrent code before and after blocks, but still execute within the method. Of course, you can easily use synchronous methods by refactoring concurrent code into separate asynchronous methods. Use this way to make the code easier to understand.