Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In <em>some</em> executions it would have the same flow as synchronizing the whole functions, sure - but for it to be truly equivalent to making the method synchronized, it would have to have the same flow for <em>all</em> executions.</p> <p>As it is, there's a possibility that another thread will grab the lock (whether for this method or some other code locking on the same monitor) half way through execution. That couldn't happen if the method itself were synchronized, therefore they're not equivalent.</p> <p>(As an aside, locking on <code>this</code> is generally considered to be bad practice anyway; I can't remember the last time I wrote a synchronized method. I lock on privately held monitors instead, so that I know my code is the only code which can possibly lock on them.)</p> <p>EDIT: To respond to your edit:</p> <blockquote> <p>All I need to know is whether I can count on all execution contexts that both threads (e.g. Thread1 and Thread2) can be in the method at the same time, e.g thread2 in the first sync block and thread1 in the second sync block to achieve concurrency</p> </blockquote> <p>Absolutely not! It's guaranteed that you <em>won't</em> have two threads both in a synchronized block synchronized on the same monitor.</p> <p>You have three sections of code: the first synchronized block, the unsynchronized part, and the second synchronized part.</p> <p>Any number of threads can be executing in the unsynchronized part at a time. For any one instance (because you're synchronizing on <code>this</code>) only one thread can be executing <em>either</em> of the synchronized blocks. If you want to achieve concurrency, you'd have to synchronize on different monitors.</p> <p>Furthermore, it sounds like you want guarantees of the scheduler letting another thread grab the lock if it was waiting for it. I don't believe there's any such guarantee - a thread executing the first block could release the lock but continue in the same timeslice and re-acquire it before any other threads got in. In some JVMs that may not happen, but I don't believe there's any guarantee around it.</p>
 

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