跳至主要内容

博文

目前显示的是 五月, 2015的博文

Singleton and Synchronization

Why synchronized in singleton I will describe what I encounter to convince you it is really needed to do so. I have the Class A in the Thread-use : Singleton s1 = Singleton.getInstance(); synchronized(s1){ while (!B.ready){ s1.wait(); } // read from singleton } Then Class B in Thread-readData : // notice the volatile static volatile boolean ready = false; Singleton s2 = Singleton.getInstance(); synchronized(s2){ // read data than write to singleton ready = true; s2.notify(); } Then Singleton : public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } This getInstance() is not synchronized now. If the first thread enter the if clause first, then the second thread get the cpu also enter it ( if clause ) when the instance are still null , so they create two Singleton and return separately . As a result, the s1 and s2 point to the different objects which cause