What is the most frequent concurrency issue you've encountered in Java?
My #1 most painful concurrency problem ever occurred when two different open source libraries did something like this:
private static final String LOCK = "LOCK"; // use matching strings
// in two different libraries
public doSomestuff() {
synchronized(LOCK) {
this.work();
}
}
At first glance, this looks like a pretty trivial synchronization example. However; because Strings are interned in Java, the literal string "LOCK"
turns out to be the same instance of java.lang.String
(even though they are declared completely disparately from each other.) The result is obviously bad.
The most common concurrency problem I've seen, is not realizing that a field written by one thread is not guaranteed to be seen by a different thread. A common application of this:
class MyThread extends Thread {
private boolean stop = false;
public void run() {
while(!stop) {
doSomeWork();
}
}
public void setStop() {
this.stop = true;
}
}
As long as stop is not volatile or setStop
and run
are not synchronized this is not guaranteed to work. This mistake is especially devilish as in 99.999% it won't matter in practice as the reader thread will eventually see the change - but we don't know how soon he saw it.
One classic problem is changing the object you're synchronizing on while synchronizing on it:
synchronized(foo) {
foo = ...
}
Other concurrent threads are then synchronizing on a different object and this block does not provide the mutual exclusion you expect.