...
Code Block |
---|
|
// ...
synchronized(m) { // Synchronize on m, not s
for(Integer k : s) {
// Do something
}
}
|
Noncompliant Code Example (nonstatic lock object for static
data)
This noncompliant code example uses a nonstatic lock object to guard access to a static
field. If two Runnable
tasks, each consisting of a thread are started, they will create two instances of the lock object and lock on each separately. This does not prevent either thread from observing an inconsistent value of field counter
because the increment operation on volatile
fields is not atomic in the absence of proper synchronization.
Code Block |
---|
|
class CountBoxes implements Runnable {
static volatile int counter;
// ...
Object lock = new Object();
public void run() {
synchronized(lock) {
counter++;
// ...
}
}
public static void main(String[] args) {
Runnable r1 = new CountBoxes();
Thread t1 = new Thread(r1);
Runnable r2 = new CountBoxes();
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
|
Noncompliant Code Example (method synchronization for static
data)
This noncompliant code example uses method synchronization to protect access to a static
class member.
Code Block |
---|
|
class CountBoxes implements Runnable {
static volatile int counter;
// ...
public synchronized void run() {
counter++;
// ...
}
// ...
}
|
The problem is that this lock is associated with each instance of the class and not with the class itself. Consequently, threads constructed using different Runnable
instances may observe inconsistent values of the counter
.
Compliant Solution (1) (static
lock object)
...