Last active
September 26, 2018 02:00
-
-
Save gotoark/166dc93a14691b66ccbdd3ef7936f6b5 to your computer and use it in GitHub Desktop.
Singleton Example
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
package singleton; | |
public class ThreadSafeSingleton { | |
//1.private Constructor | |
private ThreadSafeSingleton() { | |
} | |
//2.Only Instance of the Class | |
private static ThreadSafeSingleton instance = new ThreadSafeSingleton(); | |
//3.Public method to enable global access | |
public static synchronized ThreadSafeSingleton getClassInstance() { | |
if(instance == null){ | |
instance = new ThreadSafeSingleton(); | |
} | |
return instance; | |
} | |
// to avoid overhead by synchronized | |
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){ | |
if(instance == null){ | |
synchronized (ThreadSafeSingleton.class) { | |
if(instance == null){ | |
instance = new ThreadSafeSingleton(); | |
} | |
} | |
} | |
return instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment