...
Code Block |
---|
|
// 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 |
---|
|
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 |
---|
|
Map<IntegerMap<Integer, String>String> m = Collections.synchronizedMap(new HashMap<IntegerHashMap<Integer, String>String>());
Set<Integer>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]\] "Synchronization""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 11. Concurrency (CON) CON37-J. Never apply a lock to methods making network calls