Skip to content

Instantly share code, notes, and snippets.

@somethingnew2-0
Last active December 30, 2015 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save somethingnew2-0/7771751 to your computer and use it in GitHub Desktop.
Save somethingnew2-0/7771751 to your computer and use it in GitHub Desktop.
A kernel programmer's singleton
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();
}
}
@xtraclass
Copy link

Doesn't that mean that every call of getInstance() creates a new INSTANCE object (therefore not a singleton)?

@gwatt
Copy link

gwatt commented Dec 3, 2013

No, because of lock.

@jpaton
Copy link

jpaton commented Dec 4, 2013

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.

@somethingnew2-0
Copy link
Author

Threads are free, right? :trollface:

@somethingnew2-0
Copy link
Author

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