jeudi 28 février 2019

Java singleton concurrent issue demonstrated by debuging on byte code or assembly code

Java singleton patten:

public class Singleton {
  static Singleton instance;
  static Singleton getInstance(){
    if (instance == null) {
      synchronized(Singleton.class) {
        if (instance == null)
          instance = new Singleton();
        }
    }
    return instance;
  }
}

If there are two threads: A and B, they call getInstance(), probably one of the threads will get a instance of not complettely constructed. But if you run those pieces of code many many times, you may not get the wrong result. I guess it's because executing the byte code or assembly code is very fast. If control the executing steps, debug the byte code or assembly code line by line alternately, the wrong result can be reproduced.

Java singleton patten issue(or volatile) is talk a lot on the web. But it's hard to find some useful, authentic practice code to run arbitrary times to produce the wrong result.

Are there any useful blogs/articles tell these?

Aucun commentaire:

Enregistrer un commentaire