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(); | |
} | |
} |
No, because of lock.
Wouldn't every call to getInstance create a new thread, but after the first call, each subsequent thread would just block indefinitely on the lock. So you would leak threads.
Threads are free, right?
I wrote this to be on par with http://xkcd.com/1185/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't that mean that every call of getInstance() creates a new INSTANCE object (therefore not a singleton)?