Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot

...

Code Block
bgColor#FFcccc
// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String _lock = "one";"one";
synchronized(_lock) { /* ... */ }

...

Wiki Markup
This idea is sometimes easy to miss, especially when the Java Language Specification is misunderstood. Section 4.3.2 ""The Class Object"" of the specification \[[JLS 05|AA. Java References#JLS 05]\] describes how method synchronization works:

...

Code Block
bgColor#ccccff
synchronized(Class.forName("SuperclassName""SuperclassName")) { ... }

Finally, it is more important to recognize the entities with whom synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize on.

...

Wiki Markup
When using synchronization wrappers, the synchronization object must be the {{Collection}} object. The synchronization is necessary to enforce atomicity ([CON38-J. Ensure atomicity of thread-safe code]). This noncompliant code example demonstrates inappropriate synchronization resulting from locking on a {{Collection}} view instead of the Collection itself \[[Tutorials 08|AA. Java References#Tutorials 08]\]. 

Code Block
bgColor#FFcccc
Map&lt;IntegerMap<Integer, String&gt;String> m = Collections.synchronizedMap(new HashMap&lt;IntegerHashMap<Integer, String&gt;String>());
Set&lt;Integer&gt;Set<Integer> s = m.keySet();
synchronized(s) {  // Incorrectly synchronizes on s
  for(Integer k : s) { 
    // Do something 
  }
}

...

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Class String
\[[Pugh 08|AA. Java References#Pugh 08]\] &quot;Synchronization&quot;"Synchronization"
\[[Miller 09|AA. Java References#Miller 09]\] Locking
\[[Tutorials 08|AA. Java References#Tutorials 08]\] [Wrapper Implementations|http://java.sun.com/docs/books/tutorial/collections/implementations/wrapper.html]

...

CON35-J. Do not try to force thread shutdown&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      11. Concurrency (CON)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      CON37-J. Never apply a lock to methods making network calls