//非線程安全
這種處理方式在單線程的模式下可以很好的運行;但是在多線程模式下,可能產生問題。如果第一個線程發現成員變量爲null,準備創建對象;這是第二個線程同時也發現成員變量爲null,也會創建新對象。這就會造成在一個JVM中有多個單例類型的實例。如果這個單例類型的成員變量在運行過程中變化,會造成多個單例類型實例的不一致,產生一些很奇怪的現象。例如,某服務進程通過檢查單例對象的某個屬性來停止多個線程服務,如果存在多個單例對象的實例,就會造成部分線程服務停止,部分線程服務不能停止的情況
public class TestService{
private static TestService instance = null;
private TestService() {
}
public static TestService getInstance() {
if (instance == null) {
instance=new TestService();
}
return instance;
}
}
|
//線程安全
這種處理方式雖然引入了同步代碼,但是因爲這段同步代碼只會在最開始的時候執行一次或多次,所以對整個系統的性能不會有影響。
public class TestService{
private static TestService instance = null;
private TestService() {
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new TestService();
}
}
public static TestService getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
}
|