【发布时间】:2014-10-30 19:13:23
【问题描述】:
我有一个单例服务器实例,我很好奇我的代码是否是线程安全的。 I've read 关于不同的单例模式,我认为一般要走的路是double-checked locking 模式,如下:
public static Singleton getInstance() {
if(singleton == null) {
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
这应该是一种设置/获取单例的高效线程安全方式。我读过,获取和设置单例的最简单方法是lazy instantiation,如下所示:
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
现在我想知道我的变体是否是线程安全的。我的代码:
public static void startServer(int listeningPortNumber) throws IOException {
if (server != null) {
throw new IOException("Connection exists");
}
server = new Server(listeningPortNumber);
}
我的代码与上面的 惰性实例化 模式非常相似,但我看不出我的代码不是线程安全的。有什么我看不到的东西还是这实际上是有效的代码?
参考:http://www.javaworld.com/article/2073352/core-java/simply-singleton.html
【问题讨论】:
-
您想做什么以确保线程安全?
-
@StackFlowed 这无关紧要
-
@StackFlowed 你为什么大喊?
-
@Pshemo caps 被误按
-
@StackFlowed 我明白了。好吧,我想我真的不需要它,我只是好奇并想自学。
标签: java thread-safety singleton