Skip to content

Instantly share code, notes, and snippets.

@Coneboy-k
Created October 31, 2017 01:33
Show Gist options
  • Save Coneboy-k/22d89e60691c0bf31d6eb8c5c9dc1db2 to your computer and use it in GitHub Desktop.
Save Coneboy-k/22d89e60691c0bf31d6eb8c5c9dc1db2 to your computer and use it in GitHub Desktop.
不使用Lock 实现单例
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;
}
}
}
}
@Coneboy-k
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment