Skip to content

Instantly share code, notes, and snippets.

@adamblank
Last active October 9, 2016 06:20
Show Gist options
  • Save adamblank/a8de9e35897ac21e8ddb to your computer and use it in GitHub Desktop.
Save adamblank/a8de9e35897ac21e8ddb to your computer and use it in GitHub Desktop.
/*
* Boilerplate thread local singleton
*/
protected Singleton() {} //enforce singleton pattern with protected constructor
private static ThreadLocal<Singleton> instance = null; //the current thread instance
/** Get the singleton instance of this service
* If no instance exists for this thread, instantiate one
*
* @return
*/
public static Singleton getInstance() {
if (instance == null) {
instance = new ThreadLocal<Singleton>() {
@Override
protected Singleton initialValue() {
return new Singleton();
}
};
}
return instance.get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment