...
This noncompliant code example uses a nonstatic lock object to guard access to a static
field. If two threads 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 length
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 BoxCountBoxes(); Thread t1 = new Thread(r1); Runnable r2 = new BoxCountBoxes(); Thread t2 = new Thread(r2); t1.start(); t2.start(); } } |
...
This compliant solution declares the lock object as static
to ensure that and consequently, ensures the atomicity of the increment operation is carried out atomically using a shared lock object.
Code Block | ||
---|---|---|
| ||
class CountBoxes implements Runnable { static volatile int counter; // ... static Object lock = new Object(); // ... } |
...