[英]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.