...
Code Block |
---|
|
// ...
synchronized(m) { // Synchronize on m, not s
for(Integer k : s) { /* do something */ }
}
|
Noncompliant Code Example
This noncompliant example incorrectly uses a ReentrantLock
as the lock object.
Code Block |
---|
|
final Lock lock = new ReentrantLock();
synchronized(lock) { /* do something */ }
|
Compliant Solution
The proper mechanism to lock in this case is to explicitly use the lock()
and unlock()
methods provided by the ReentrantLock
class.
Code Block |
---|
|
final Lock lock = new ReentrantLock();
lock.lock();
try {
// ...
} finally {
lock.unlock();
}
|
Risk Assessment
Synchronizing on an incorrect variable can provide a false sense of thread safety and result in nondeterministic behavior.
...
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] Class String
\[[Pugh 08|AA. Java References#Pugh 08]\] "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] |
...