What's better about synchronized methods than synchronized blocks when synchronized on threads?

Asked 2 years ago, Updated 2 years ago, 163 views

Please show me an example of how the Synchronized method is better than Synchronized Block in the thread.

multithreading java synchronized concurrency

2022-09-22 13:39

1 Answers

The Synchronized method has no special advantage over blocks. If I have to pick one, I don't have to include the object reference this but I don't think that's an advantage.

methods:

public synchronized void method() {/ If it was a block, this must be added
    ...
    ...
    ...
} 

Block:

public void method() { 
    Synchronized(this) { // put this
        ....
        ....
        ....
    }  
}

Block is better than the method. Synchronized blocks are more flexible in many ways than methods. This is because the Synchronized method locks the entire method, but blocks can lock specific parts using other objects.

//Lock the entire object 
... 
private synchronized void someInputRelatedWork() {
    ... 
}
private synchronized void someOutputRelatedWork() {
    ... 
}

Vs.

// Lock only certain parts
Object inputLock = new Object();
Object outputLock = new Object();

private void someInputRelatedWork() {
    synchronize(inputLock) { 
        ... 
    } 
}
private void someOutputRelatedWork() {
    synchronize(outputLock) { 
        ... 
    }
}

Also, if you use Synchronized block, you can lock only the necessary parts within the method like the code below.

 private void method() {
            ... Code
            ... Code          
        ... Code
    synchronized( lock ) { 
             ... Code
            }
            ... Code 
            ... Code 
            ... Code
            ... Code
}


2022-09-22 13:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.