February 11, 2009

Java Concurrency: How to Share Data Between Threads.

One of challenging thing of writing multi thread safe application is to share data between different threads. The problem is twofold:
  • Visibility, i.e. one reading thread must see the latest value that another thread writes to.
  • Atomicity, e.g. one thread increment a shared class variable must be consistent with another thread setting the same class variable to a new value.
The simplest case is when one class variable is not depending on its previous state/value. A typical example is a boolean value that is explicit set and does not make use of its previous value.
public class Worker {

private volatile boolean working = false;

private long workCount = 0L;

public boolean isWorking() {
return working;
}

public void startWorking() {
working = true;
work();
}

public void stopWorking() {
working = false;
}

private void work() {
while (working) {
 ++workCount;
}
}
}
In this example we do not use synchronization, but instead we use volatile. What volatile do is force the JVM to store the variable value in memory, instead of local registers that each thread otherwise read and writes from. What is imported to not forget about volatile it does not upright hold Atomicity, so if the class variable was depending on it's previous state/value, this implementation would not be thread safe. Instead one should use one of the classes in java.util.concurrent.atomic package.

No comments: