Last active
December 30, 2015 03:49
-
-
Save somethingnew2-0/7771751 to your computer and use it in GitHub Desktop.
A kernel programmer's singleton
This file contains 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
import java.util.concurrent.locks.ReentrantLock; | |
public class Singleton implements Runnable { | |
private static Singleton INSTANCE; | |
private static ReentrantLock LOCK = new ReentrantLock(); | |
private Singleton() { } | |
public Singleton getInstance() { | |
new Thread(this).run(); | |
while(INSTANCE == null) { | |
Thread.yield(); | |
} | |
return INSTANCE; | |
} | |
@Override | |
public void run() { | |
LOCK.lock(); | |
INSTANCE = new Singleton(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Threads are free, right?