Created
October 31, 2017 01:33
-
-
Save Coneboy-k/22d89e60691c0bf31d6eb8c5c9dc1db2 to your computer and use it in GitHub Desktop.
不使用Lock 实现单例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Singleton { | |
private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>(); | |
private Singleton() {} | |
public static Singleton getInstance() { | |
for (;;) { | |
Singleton singleton = INSTANCE.get(); | |
if (null != singleton) { | |
return singleton; | |
} | |
singleton = new Singleton(); | |
if (INSTANCE.compareAndSet(null, singleton)) { | |
return singleton; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from http://www.hollischuang.com/archives/1866