Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoid synchronized(this) in Java?
    text
    copied!<p>Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that <code>synchronized(this)</code> should be avoided. Instead, they claim, a lock on a private reference is to be preferred.</p> <p>Some of the given reasons are:</p> <ul> <li><a href="https://stackoverflow.com/questions/416183/in-java-critical-sections-what-should-i-synchronize-on#416198">some <em>evil code</em> may steal your lock</a> (very popular this one, also has an "accidentally" variant)</li> <li><a href="https://stackoverflow.com/questions/309631/what-cases-require-synchronized-method-access-in-java#309677">all synchronized methods within the same class use the exact same lock, which reduces throughput</a></li> <li><a href="https://stackoverflow.com/questions/439302/allowing-a-method-to-lock-its-parent-object-in-java#439317">you are (unnecessarily) exposing too much information</a></li> </ul> <p>Other people, including me, argue that <code>synchronized(this)</code> is an idiom that is used a lot (also in Java libraries), is safe and well understood. It should not be avoided because you have a bug and you don't have a clue of what is going on in your multithreaded program. In other words: if it is applicable, then use it.</p> <p>I am interested in seeing some real-world examples (no foobar stuff) where avoiding a lock on <code>this</code> is preferable when <code>synchronized(this)</code> would also do the job.</p> <p>Therefore: <strong>should you always avoid <code>synchronized(this)</code> and replace it with a lock on a private reference?</strong> </p> <hr> <p>Some further info (updated as answers are given):</p> <ul> <li>we are talking about instance synchronization</li> <li>both implicit (<code>synchronized</code> methods) and explicit form of <code>synchronized(this)</code> are considered</li> <li>if you quote Bloch or other authorities on the subject, don't leave out the parts you don't like (e.g. Effective Java, item on Thread Safety: <em>Typically it is the lock on the instance itself, but there are exceptions.)</em></li> <li>if you need granularity in your locking other than <code>synchronized(this)</code> provides, then <code>synchronized(this)</code> is not applicable so that's not the issue</li> </ul>
 

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