Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created February 15, 2014 16:27
Show Gist options
  • Save adohe-zz/9021605 to your computer and use it in GitHub Desktop.
Save adohe-zz/9021605 to your computer and use it in GitHub Desktop.
use case of singleton class in Java
public class ApplicationCache {
//NO Lazy Initialization
private static final ApplicationCache INSTANCE = new ApplicationCache();
//Check the INSTANCE to avoid the reflect call
private ApplicationCache() {
if(INSTANCE != null)
throw new IllegalStateException("Exist Already");
}
}
class ConnectionPool {
//Lazy Initialization
private static volatile ConnectionPool instance;
public static ConnectionPool getInstance() {
if(instance == null) {
//synchronized on class level lock
synchronized(ConnectionPool.class) {
if(instance == null) {
instance = new ConnectionPool();
}
}
}
return instance;
}
private ConnectionPool() {
if(instance != null) {
throw new IllegalStateException("Exist Already");
}
}
}
//Use Enum maybe the best solution
public enum Connection {
INSTANCE;
public void connect() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment