...
Code Block | ||
---|---|---|
| ||
public final class CountBoxes implements Runnable {
private static volatile int counter;
// ...
private final Object lock = new Object();
@Override public void run() {
synchronized(lock) {
counter++;
// ...
}
}
public static void main(String[] args) {
for(int i = 0; i < 2; i++) {
new Thread(new CountBoxes()).start();
}
}
}
|
This example does not prevent either thread from observing an inconsistent value of counter
because the increment operation on volatile fields is not - atomic in the absence of proper synchronization (see guideline VNA02-J. Ensure that compound operations on shared variables are atomic).
...
Code Block | ||
---|---|---|
| ||
public class CountBoxes implements Runnable {
private static int counter;
// ...
private static final Object lock = new Object();
public void run() {
synchronized(lock) {
counter++;
// ...
}
}
// ...
}
|
There is no need to declare the counter
variable volatile when using synchronization.
...