...
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();
}
}
|
Compliant Solution (1) (static
lock object)
This compliant solution declares the lock object as static
and consequently, ensures the atomicity of the increment operation.
Code Block |
---|
|
class CountBoxes implements Runnable {
static volatile int counter;
// ...
static final Object lock = new Object();
// ...
}
|
There is no requirement of declaring the counter
variable as volatile
when synchronization is used.
Compliant Solution (2)(intrinsic lock of class)
This compliant solution uses the intrinsic lock of the class to synchronize the increment operation.
Code Block |
---|
|
class CountBoxes implements Runnable {
static int counter;
// ...
public void run() {
synchronized(CountBoxes.class) {
counter++;
// ...
}
}
// ...
}
|
Noncompliant Code Example (ReentrantLock
lock object)
...