...
Finally, it is important to recognize the entities with which synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize on.
Noncompliant Code Example
Wiki Markup |
---|
When using synchronization wrappers, the synchronization object needs to be the {{Collection}} object. The synchronization is necessary to enforce atomicity ([CON38-J. Ensure atomicity of thread-safe code]). This noncompliant 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<Integer, String> m = Collections.synchronizedMap(new HashMap<Integer, String>());
Set<Integer> s = m.keySet();
synchronized(s) { // Incorrectly synchronizes on s
for(Integer k : s) { /* do something */ }
}
|
Compliant Solution
This compliant solution correctly synchronizes on the Collection
object instead of the Collection
view.
Code Block | ||
---|---|---|
| ||
// ...
synchronized(m) { // Synchronize on m, not s
for(Integer k : s) { /* do something */ }
}
|
Risk Assessment
Synchronizing on an incorrect variable can provide a false sense of thread safety and result in nondeterministic behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON36-J | medium | probable | low | P12 | L1 |
...
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] Class String
\[[Pugh 08|AA. Java References#Pugh 08]\] "Synchronization"
\[[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 08. Concurrency (CON) 08. Concurrency (CON)