java - Is there an advantage to use a Synchronized Method instead of a Synchronized Block? -


can 1 tell me advantage of synchronized method on synchronized block example?

can 1 tell me advantage of synchronized method on synchronized block example?thanks.

there not clear advantage of using synchronized method on block.

perhaps 1 ( wouldn't call advantage ) don't need include object reference this.

method:

public synchronized void method() { // blocks "this" here....      ...     ...     ... } // here 

block:

public void method() {      synchronized( ) { // blocks "this" here ....          ....         ....         ....     }  // here... } 

see? no advantage @ all.

blocks do have advantages on methods though, in flexibility because can use object lock whereas syncing method lock entire object.

compare:

// locks whole object ...  private synchronized void someinputrelatedwork() {     ...  } private synchronized void someoutputrelatedwork() {     ...  } 

vs.

// using specific locks object inputlock = new object(); object outputlock = new object();  private void someinputrelatedwork() {     synchronize(inputlock) {          ...      }  } private void someoutputrelatedwork() {     synchronize(outputlock) {          ...      } } 

also if method grows can still keep synchronized section separated:

 private void method() {      ... code here      ... code here      ... code here     synchronized( lock ) {          ... few lines of code here     }      ... code here      ... code here      ... code here      ... code here } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -