Search code examples
javamultithreadingconcurrency

What is the most frequent concurrency issue you've encountered in Java?


This is a poll of sorts about common concurrency problems in Java. An example might be the classic deadlock or race condition or perhaps EDT threading bugs in Swing. I'm interested both in a breadth of possible issues but also in what issues are most common. So, please leave one specific answer of a Java concurrency bug per comment and vote up if you see one you've encountered.


Solution

  • 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.