Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p><em>Can anyone tell me the advantage of the synchronized method over the synchronized block with an example? Thanks.</em></p> </blockquote> <p>There is not a clear advantage of using synchronized method over the block. </p> <p>Perhaps the only one ( but I wouldn't call it an advantage ) is you don't need to include the object reference <code>this</code>.</p> <p>Method:</p> <pre><code>public synchronized void method() { // blocks "this" from here.... ... ... ... } // to here </code></pre> <p>Block:</p> <pre><code>public void method() { synchronized( this ) { // blocks "this" from here .... .... .... .... } // to here... } </code></pre> <p>See? No advantage at all. </p> <p>Blocks <strong>do</strong> have advantages over methods though, mostly in flexibility because you can use another object as lock whereas syncing the method would lock the entire object.</p> <p>Compare: </p> <pre><code>// locks the whole object ... private synchronized void someInputRelatedWork() { ... } private synchronized void someOutputRelatedWork() { ... } </code></pre> <p>vs. </p> <pre><code>// Using specific locks Object inputLock = new Object(); Object outputLock = new Object(); private void someInputRelatedWork() { synchronized(inputLock) { ... } } private void someOutputRelatedWork() { synchronized(outputLock) { ... } } </code></pre> <p>Also if the method grows you can still keep the synchronized section separated:</p> <pre><code> private void method() { ... code here ... code here ... code here synchronized( lock ) { ... very few lines of code here } ... code here ... code here ... code here ... code here } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload