The same class behaves incorrectly in a multithreaded environment. Multiple threads can call the creation method simultaneously and get several instances of Singleton class.
packagerefactoring_guru.singleton.example.non_thread_safe;publicclassDemoMultiThread {publicstaticvoidmain(String[] args) {System.out.println("If you see the same value, then singleton was reused (yay!)"+"\n"+"If you see different values, then 2 singletons were created (booo!!)"+"\n\n"+"RESULT:"+"\n");Thread threadFoo =newThread(new ThreadFoo());Thread threadBar =newThread(new ThreadBar());threadFoo.start();threadBar.start(); }staticclassThreadFooimplementsRunnable { @Overridepublicvoidrun() {Singleton singleton =Singleton.getInstance("FOO");System.out.println(singleton.value); } }staticclassThreadBarimplementsRunnable { @Overridepublicvoidrun() {Singleton singleton =Singleton.getInstance("BAR");System.out.println(singleton.value); } }}
OutputDemoMultiThread.txt: Execution result
If you see the same value, then singleton was reused (yay!)
If you see different values, then 2 singletons were created (booo!!)
RESULT:
FOO
BAR