[英]Java Simple Way to Create Application Singleton
我正在嘗試為我的 Java 應用程序創建一個全局連接池。
我的問題是,當我使用以下方法時:
package mypackage;
public class Singleton
{
private static MyPool connPool;
private Singleton() {}
public MyPool getPool() {
if (connPool == null)
connPool = new MyPool();
return connPool;
}
}
現在,如果我有兩個類 A 和 B 導入 Singleton class 上面使用
import mypackage.Singleton;
然后我將最終調用new MyPool()
兩次,這意味着我將打開與我的資源(例如數據庫)的雙倍連接。 如何確保在我的應用程序中只創建一次池?
我在互聯網上發現了一些使用反射來完成此任務的復雜方法。 有沒有更簡單(和/或更好)的方法?
我認為您正在尋找 Singleton class 的線程安全實現。 當然,實現這一點的方法是使用枚舉,但對於您的情況,您可以實現雙重檢查鎖定以確保沒有兩個線程可以同時調用 new MyPool()。
另外,我認為在您的代碼中,您實際上是在實現工廠 class,而不是真正的 singleton。 您的 MyPool 與 Singleton 不同,class 可能具有公共構造函數。
我已對評論進行了適當的更改。
雙重檢查鎖定基本上只是檢查null檢查前后的線程安全性,因為整個方法是不同步的,所以兩個線程確實可以在同步塊之后得到條件中的null值,因此是第二次同步。
另外,我認為您的 getPool() 應該是static 。 如果沒有明確的 Singleton 的 object,您將無法調用 getPool(),我認為您不需要。
修正版:
package mypackage;
public class Singleton{
// Instance should be of type Singleton, not MyPool
private static Singleton connPool;
private Singleton() {}
// *static* factory method
public static Singleton getPool() {
// Double-check-locking start
synchronized(Singleton.class){
if (connPool == null){
// Double-check-locking end
synchronized(Singleton.class){
//create Singleton instance, not MyPool
connPool = new Singleton();
}
}
}
return connPool;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.