Created
February 15, 2014 16:27
-
-
Save adohe-zz/9021605 to your computer and use it in GitHub Desktop.
use case of singleton class in Java
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
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