What is the preferred way to work with Singleton class in multithreaded environment?
Suppose if I have 3 threads, and all of them try to access getInstance() method of singleton class at the same time -
What would happen if no synchronization is maintained?
Is it good practice to use synchronized getInstance() method or use synchronized block inside getInstance().
Please advise if there is any other way out.
If you're talking about threadsafe, lazy initialization of the singleton, here is a cool code pattern to use that accomplishes 100% threadsafe lazy initialization without any synchronization code:
public class MySingleton {
private static class MyWrapper {
static MySingleton INSTANCE = new MySingleton();
}
private MySingleton () {}
public static MySingleton getInstance() {
return MyWrapper.INSTANCE;
}
}
This will instantiate the singleton only when getInstance() is called, and it's 100% threadsafe! It's a classic.
It works because the class loader has its own synchronization for handling static initialization of classes: You are guaranteed that all static initialization has completed before the class is used, and in this code the class is only used within the getInstance() method, so that's when the class loaded loads the inner class.
As an aside, I look forward to the day when a #Singleton annotation exists that handles such issues.
Edited:
A particular disbeliever has claimed that the wrapper class "does nothing". Here is proof that it does matter, albeit under special circumstances.
The basic difference is that with the wrapper class version, the singleton instance is created when the wrapper class is loaded, which when the first call the getInstance() is made, but with the non-wrapped version - ie a simple static initialization - the instance is created when the main class is loaded.
If you have only simple invocation of the getInstance() method, then there is almost no difference - the difference would be that all other sttic initialization would have completed before the instance is created when using the wrapped version, but this is easily dealt with by simply having the static instance variable listed last in the source.
However, if you are loading the class by name, the story is quite different. Invoking Class.forName(className) on a class cuasing static initialization to occur, so if the singleton class to be used is a property of your server, with the simple version the static instance will be created when Class.forName() is called, not when getInstance() is called. I admit this is a little contrived, as you need to use reflection to get the instance, but nevertheless here's some complete working code that demonstrates my contention (each of the following classes is a top-level class):
public abstract class BaseSingleton {
private long createdAt = System.currentTimeMillis();
public String toString() {
return getClass().getSimpleName() + " was created " + (System.currentTimeMillis() - createdAt) + " ms ago";
}
}
public class EagerSingleton extends BaseSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
public static EagerSingleton getInstance() {
return INSTANCE;
}
}
public class LazySingleton extends BaseSingleton {
private static class Loader {
static final LazySingleton INSTANCE = new LazySingleton();
}
public static LazySingleton getInstance() {
return Loader.INSTANCE;
}
}
And the main:
public static void main(String[] args) throws Exception {
// Load the class - assume the name comes from a system property etc
Class<? extends BaseSingleton> lazyClazz = (Class<? extends BaseSingleton>) Class.forName("com.mypackage.LazySingleton");
Class<? extends BaseSingleton> eagerClazz = (Class<? extends BaseSingleton>) Class.forName("com.mypackage.EagerSingleton");
Thread.sleep(1000); // Introduce some delay between loading class and calling getInstance()
// Invoke the getInstace method on the class
BaseSingleton lazySingleton = (BaseSingleton) lazyClazz.getMethod("getInstance").invoke(lazyClazz);
BaseSingleton eagerSingleton = (BaseSingleton) eagerClazz.getMethod("getInstance").invoke(eagerClazz);
System.out.println(lazySingleton);
System.out.println(eagerSingleton);
}
Output:
LazySingleton was created 0 ms ago
EagerSingleton was created 1001 ms ago
As you can see, the non-wrapped, simple implementation is created when Class.forName() is called, which may be before the static initialization is ready to be executed.
The task is non-trivial in theory, given that you want to make it truly thread safe.
A very nice paper on the matter is found # IBM
Just getting the singleton does not need any sync, since it's just a read. So, just synchronize the setting of the Sync would do. Unless two treads try to create the singleton at start up at the same time, then you need to make sure check if the instance is set twice (one outside and one inside the sync) to avoid resetting the instance in a worst case scenario.
Then you might need to take into account how JIT (Just-in-time) compilers handle out-of-order writes. This code will be somewhat near the solution, although won't be 100% thread safe anyway:
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
Singleton inst = instance;
if (inst == null) {
synchronized(Singleton.class) {
instance = new Singleton();
}
}
}
}
return instance;
}
So, you should perhaps resort to something less lazy:
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
Or, a bit more bloated, but a more flexible way is to avoid using static singletons and use an injection framework such as Spring to manage instantiation of "singleton-ish" objects (and you can configure lazy initialization).
You need synchronization inside getInstance only if you initialize your singleton lazily. If you could create an instance before the threads are started, you can drop synchronization in the getter, because the reference becomes immutable. Of course if the singleton object itself is mutable, you would need to synchronize its methods which access information that can be changed concurrently.
This question really depends on how and when your instance is created. If your getInstance method lazily initializes:
if(instance == null){
instance = new Instance();
}
return instance
Then you must synchronize or you could end up with multiple instances. This problem is usually treated in talks on Double Checked Locking.
Otherwise if you create a static instance up front
private static Instance INSTANCE = new Instance();
then no synchronization of the getInstance() method is necessary.
The best way as described in effective java is:
public class Singelton {
private static final Singelton singleObject = new Singelton();
public Singelton getInstance(){
return singleObject;
}
}
No need of synchronization.
Nobody uses Enums as suggested in Effective Java?
If you are sure that your java runtime is using the new JMM (Java memory model, probably newer than 5.0), double check lock is just fine, but add a volatile in front of instance. Otherwise, you'd better use static internal class as Bohemian said, or Enum in 'Effective Java' as Florian Salihovic said.
For simplicity, I think using enum class is a better way. We don't need to do any synchronization. Java by construct, always ensure that there is only one constant created, no matter how many threads are trying to access it.
FYI, In some case you need to swap out singleton with other implementation. Then we need to modify class, which is violation of Open Close principal.Problem with singleton is, you can't extend the class because of having private constructor. So, it's a better practice that client is talking via interface.
Implementation of Singleton with enum class and Interface:
Client.java
public class Client{
public static void main(String args[]){
SingletonIface instance = EnumSingleton.INSTANCE;
instance.operationOnInstance("1");
}
}
SingletonIface.java
public interface SingletonIface {
public void operationOnInstance(String newState);
}
EnumSingleton.java
public enum EnumSingleton implements SingletonIface{
INSTANCE;
#Override
public void operationOnInstance(String newState) {
System.out.println("I am Enum based Singleton");
}
}
The Answer is already accepted here, But i would like to share the test to answer your 1st question.
What would happen if no synchronization is maintained?
Here is the SingletonTest class which will be completely disaster when you run in multi Threaded Environment.
/**
* #author MILAN
*/
public class SingletonTest
{
private static final int PROCESSOR_COUNT = Runtime.getRuntime().availableProcessors();
private static final Thread[] THREADS = new Thread[PROCESSOR_COUNT];
private static int instancesCount = 0;
private static SingletonTest instance = null;
/**
* private constructor to prevent Creation of Object from Outside of the
* This class.
*/
private SingletonTest()
{
}
/**
* return the instance only if it does not exist
*/
public static SingletonTest getInstance()
{
if (instance == null)
{
instancesCount++;
instance = new SingletonTest();
}
return instance;
}
/**
* reset instancesCount and instance.
*/
private static void reset()
{
instancesCount = 0;
instance = null;
}
/**
* validate system to run the test
*/
private static void validate()
{
if (SingletonTest.PROCESSOR_COUNT < 2)
{
System.out.print("PROCESSOR_COUNT Must be >= 2 to Run the test.");
System.exit(0);
}
}
public static void main(String... args)
{
validate();
System.out.printf("Summary :: PROCESSOR_COUNT %s, Running Test with %s of Threads. %n", PROCESSOR_COUNT, PROCESSOR_COUNT);
long currentMili = System.currentTimeMillis();
int testCount = 0;
do
{
reset();
for (int i = 0; i < PROCESSOR_COUNT; i++)
THREADS[i] = new Thread(SingletonTest::getInstance);
for (int i = 0; i < PROCESSOR_COUNT; i++)
THREADS[i].start();
for (int i = 0; i < PROCESSOR_COUNT; i++)
try
{
THREADS[i].join();
}
catch (InterruptedException e)
{
e.printStackTrace();
Thread.currentThread().interrupt();
}
testCount++;
}
while (instancesCount <= 1 && testCount < Integer.MAX_VALUE);
System.out.printf("Singleton Pattern is broken after %d try. %nNumber of instances count is %d. %nTest duration %dms", testCount, instancesCount, System.currentTimeMillis() - currentMili);
}
}
Output of the program is clearly shows that you need handle this using getInstance as synchronized or add synchronized lock enclosing new SingletonTest.
Summary :: PROCESSOR_COUNT 32, Running Test with 32 of Threads.
Singleton Pattern is broken after 133 try.
Number of instance count is 30.
Test duration 500ms
Related
Looks I miss something in my tests (Robolectrics|Powermockito).
I have following class with Singleton:
public class Core{
private static Core instance = new Core();
public static Core getInstance() {
return instance;
}
public static void destroy(){
instance = null;
}
}
In my tests I kill the instance with Core.destroy()
and therefore Core.getInstance() returns null.
So every test I want to re-generate instance again. I do the following:
Constructor<Core> constructor = Core.class.getDeclaredConstructor();
constructor.setAccessible(true);
Core newCore = constructor.newInstance();
So now newCore is initialized but Core.getInstance() still returns null.
How to initialize properly Core -> instance?
There is an important point that I often try to explain to people when talking about singletons:
There's a difference between a singleton and something that you will only create 1 instance of. And, often, when you think you want a singleton, actually you just want something that you will only create 1 instance of.
The difference between these two things is perhaps not apparent at first, but important to realize, especially when you find yourself in a position where you need to purge the internal state of a singleton between tests.
If you have a singleton - a true singleton - there is, by definition, one instance that can exist in the JVM. If this has mutable state, this is problematic, because it means that you have to care about that state. In tests, you have to clear state between runs to remove any effects owing to the ordering of test execution; and you have to run your tests serially.
If you use dependency injection (as in the concept, not any particular framework like Guice, Dagger, Spring etc), it doesn't matter to classes using the instance where that instance came from: you, as a client of the class, get control over its life cycle. So, whereas your production code uses the same instance in all places, your testing code can use separate instances - thus they are decoupled - and often you don't even have to worry about cleaning up state at all, because your next test case can simply create a new instance of the class.
So, instead of code using your Core class like so:
class MyClass {
void foo() {
Core core = Core.getInstance();
// ... do stuff with the Core instance.
}
}
you can write it instead like:
class MyClass {
private final Core core;
MyClass(Core core) { this.core = core; }
void foo() {
// ... do stuff with the Core instance.
}
}
and you have broken the static binding between MyClass and Core. You can instantiate MyClass in tests with separate instances of Core:
MyClass myClass = new MyClass(new Core());
// Assert something...
or, if multiple instances need to interact with the same instance of Core:
Core core = new Core();
MyClass myClass = new MyClass(core);
MyOtherClass myOtherClass = new MyOtherClass(core);
// Assert something...
You should make the constructor private so that code using you singleton class cannot create an instance using it and they should only get an instance using the getInstance() method.
Also the lifetime of a singleton object is typically tied to the JVM, as there should be a single instance of a singleton class per JVM. So if you can destroy and re-create the instance it is not a true Singleton IMO, so I assume you only want to re-create the instance for testing.
To re-create the singleton from your test classes after calling the destroy() method you can get the Field of the class having the instance of your class. Using that Field you can set it to the new instance you created:
public static void main(String[] args) throws Exception {
System.out.println(Core.getInstance()); //gets instance
Core.destroy();
System.out.println(Core.getInstance()); // null
reinitializeInstance(Core.class);
System.out.println(Core.getInstance()); //gets instance
}
public static void reinitializeInstance(Class<Core> clazz) {
try {
Constructor<Core> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
Core newCore = constructor.newInstance();
Field field = Core.class.getDeclaredField("instance"); //gets the instance field
field.setAccessible(true);
field.set(newCore, newCore);
} catch (Exception e) {
e.printStackTrace();
}
}
And your Singleton class:
class Core {
private static Core instance = new Core();
// To prevent reflection from creating a new instance without destroying the first one
private Core() {
if(instance != null){
throw new IllegalStateException("Instance already exists!");
}
}
public static Core getInstance() {
return instance;
}
public static void destroy() {
instance = null;
}
}
public class Core {
private static class SingletonHolder {
private static AtomicReference<Core> instance = new AtomicReference(new Core());
}
public static Core getInstance() {
return SingletonHolder.instance.get();
}
public static void destroy() {
SingletonHolder.instance.set(null);
}
public static void reset() {
SingletonHolder.instance.compareAndSet(null, new Core());
}
}
Using an extra "superfluous" inner class is done for concurrent initialisation, ensuring that the static field is initialized once.
Changing the instance (destroy, my reset) needs some kind of synchronisation for objects.
Instead of the more costly synchronize one can use an AtomicReference.
compareAndSet does not set the instance with a new value, if there is already an old value.
It is also worth having
Optional<Core> getInstance() { ... }
So the usage is safe-guarded.
Core.getInstance().ifPresent(core -> { ... core ... });
First of all you're making Core constructor accessible, but it's public by default already.
Second, when your calling the constructor, it just creates a new instance of Core, which does nothing to instance, because constructor, created by default is empty and because constructor is not the place to initialize Singleton.
If you want to refresh singleton instance you should have a dedicated method for that.
How about this pattern instead?
public class Core{
private static Core instance;
public static Core getInstance() {
if(instance == null) instance = new Core();
return instance;
}
public static void destroy(){
instance = null;
}
}
And if you only want to destory in tests, you can remove "public" from your destroy() method
How does Singleton behave when two threads call the "getInstance()" at the same time? What are the best practices to protect it?
This is only an issue at all if you use lazy initialization on the singleton. If you use eager initialization then the JVM guarantees to sort it all out for you.
For lazy initialization you need to either synchronize (although you can make it volatile and use double-check locking to avoid synchronized blocks all the time) or embed it within an inner class where it is not lazy initialized.
peter.petrov's answer now covers most of the options well, there is one final approach to thread safe lazy initialization though that is not covered and it is probably the neatest one.
public class Singleton {
// Prevent anyone else creating me as I'm a singleton
private Singleton() {
}
// Hold the reference to the singleton instance inside a static inner class
private static class SingletonHolder {
static Singleton instance = new Singleton();
}
// Return the reference from inside the inner class
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Java does lazy loading on classes, they are only loaded when first accessed. This applies to inner classes too...
Firstly, two threads can't call the method at the "same time" - one will be deemed to call it first... called a "race condition".
Next, any properly implemented singleton will handle a race condition cleanly. IMHO, this is the cleanest way to implement a thread-safe singleton without synchronization:
public class MySingleton {
private static class Holder {
static final MySingleton INSTANCE = new MySingleton ();
}
public static MySingleton getInstance() {
return Holder.INSTANCE;
}
// rest of class omitted
}
This is called the initialization-on-demand holder idiom.
1) If you want lazy init, I think a good practice is to synchronize the getInstance body on a private static final Object instance which is member of the same class (you may name it LOCK e.g.).
2) If you don't need lazy init you can just instantiate your singleton instance at class load time. Then there's no need of any synchronization in getInstance.
Sample of 1) without using DCL (double-checked locking)
Note 1: This one avoids the complexity of using DCL by paying some extra price with respect to performance.
Note 2: This version is OK on JDK < 5 as well as on JDK >= 5.
public class Singleton {
private static final Object LOCK = new Object();
private static Singleton instance = null;
public static Singleton getInstance(){
synchronized(LOCK){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
private Singleton(){
// code to init this
}
}
Sample of 1) using DCL
Note 1: This is OK on JDK >= 5 but not on JDK < 5.
Note 2: Note the volatile keyword used, this is important.
public class Singleton {
private static final Object LOCK = new Object();
private static volatile Singleton instance = null;
public static Singleton getInstance(){
if (instance == null){
synchronized(LOCK){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
private Singleton(){
// code to init this
}
}
Sample of 2)
Note 1: This is the most simple version.
Note 2: Works on any JDK version.
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
private Singleton(){
// code to init this
}
}
References:
1) Older JDK versions (JDK < 5)
http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html
2) More recent updates on DCL
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
public class Singleton{
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
When the getInstance method is invoked for the first time, it reads Holder.INSTANCE for the first time, causing the Holder class to get initialized. The beauty of this idiom is that the getInstance method is not synchronized and performs only a field access.This is called lazy initialization. You might think that Holder class should also be loaded by the class loader when Singleton class is loaded because Holder class is static. Loading a top-level class does not automatically load any nested types within,Unless there's some other initialization that occurs during the top-level initialization, like if your top-level class has a static field that needs to be initialized with a reference to an instance of the nested class.
Synchronize access of getInstance.
Class TestSingleton {
private static volatile TestSingleton singletonObj = null;
private TestSingleton (){ // make constructor private
}
public static getInstance(){
TestSingleton obj = singletonObj ;
if(obj == null) {
synchronized(lock) { // while we were waiting for the lock, another
obj = instance; // thread may have instantiated the object
if(obj == null) {
obj = new TestSingleton();
instance = obj ;
}
}
}
public doSomeWork(){ // implementation
}
}
I am trying to implement an example of the singleton pattern. One of our questions is to run two threads each calling getInstance() and to verify only one instance of the Singleton object was created.
Here is my Singleton code;
public class OurSingleton {
static OurSingleton ourSingleton;
static int instanceCounter;
private OurSingleton(){
instanceCounter++;
}
public static synchronized OurSingleton GetSingletonInstance(){
if( ourSingleton == null){
ourSingleton = new OurSingleton();
}
return ourSingleton;
}
public static int getCounter() {
return instanceCounter;
}
}
And my main;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
OurSingleton mySingleton = null;
Thread one = new Thread(new GetSingletonInstance(mySingleton));
Thread two = new Thread(new GetSingletonInstance(mySingleton));
one.start();
two.start();
System.out.println("Main: " + mySingleton.getCounter());
}
}
class GetSingletonInstance implements Runnable {
int count = 0;
OurSingleton singleton;
public GetSingletonInstance(OurSingleton ourSingleton){
singleton = ourSingleton;
}
#Override
public void run() {
try {
while (count < 5000000) {
singleton.getSingletonInstance();
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Thread: " + singleton.getCounter());
}
}
When I run this code I get the following output;
Main: 0 Thread: 1 Thread: 1
Can somebody explain the reason for this output? I thought only a single instance of Singleton existed across the board. Does this mean another object is being created in the threads ?? Any advice is appreciated !
You should avoid synchronizing the getInstance method (because it's just an unnecessary overhead just to get the instance once it has been initialized). Following is the recommended way for lazy-initializing singleton:
public class OurSingleton {
private OurSingleton() { }
public static OurSingleton getInstance() {
return Holder.instance;
}
private static class Holder {
private static OurSingleton instance = new OurSingleton();
}
}
thought only a single instance of Singleton existed across the board.
Does this mean another object is being created in the threads ??
Only one instance of singleton exists in the JVM; each of your threads displays the fact that there is only one instance.
The easiest and safest way to implement the Singleton Pattern in Java is by using enums:
public enum MySingleton {
INSTANCE;
public void doStuffHere() {
//...
}
}
public class ClientClass {
public void myMethod() {
MySingleton mySingleton = MySingleton.INSTANCE;
mySingleton.doStuff();
}
}
You have only one instance of MySingleton and it is thread-safe.
You have created 2 instances of thread from the same class. Each one prints number of instances of your singleton object. The number is 1 that means that you indeed created only one instance, so that your singleton is implemented correctly.
You printed this twice because you created 2 threads.
If you want to avoid confusing move line System.out.println(...) to your main method.
There is only one OurSingleton instance, but the class getSingletonInstance (USE PROPER CAPS!) is not a singleton itself. And it is the one where you put the counter.
I would explain this so:
When you loaded the class OurSingleton, the static counter getInstanceCounter is initialized to zero.Then how many ever times you get a new instance of the class, the counter is always 1, indicating that you have indeed a singleton.
I would suggest making the following changes
Make the static variables in Singleton private: ourSingleton, getInstanceCounter
Remove the synchronized keyword on the method, since its an unnecessary overhead
Look at the other answer for how to do this better, for your question why are you getting this output
Main: 0
Thread: 1
Thread: 1
with the code
static int getInstanceCounter;
you are setting declaring and setting an static variable to zero. So before any instance of OurSingleton has been created getInstanceCounter has a value of zero.
When you call
System.out.println("Main: " + mySingleton.getCounter());
No instance of OurSignleton has been created so mySignleton.getCounter() is still zero.
Running of either or both threads will cause one instance of OurSingleton to be created and getInstanceCounter will be one.
Your singleton is working. Though better ways have been mentioned in other answers.
As an aside a few things about your code which may seem nit picky but will help other people read your code.
Please make variable private
static int getInstanceCounter; =>
private static int getInstanceCounter;
Variables should not be named with get
private static int getInstanceCounter; =>
private static int instanceCounter;
Don't refer to static methods on an instance of a class
mySingleton.getCounter() =>
OurSingleton.getCount()
This also means that the variable mySingleton which is never assigned a value should never be referenced and should be deleted.
public GetSingletonInstance(OurSingleton ourSingleton){
singleton = ourSingleton;
}
=>
public GetSingletonInstance(){
singleton = OurSingleton.getInstance();
}
The access to OurSingleton.getInstanceCounter (static member) via OurSingleton.getCounter () (static member function) is not synchronized. That is the only thing that matters. The remainder of your program is simply complicating things. Note that in main you are via mySingleton.getCounter () calling a static function on a null pointer! mySingleton never has another value than null.
You should use enum to implement the singleton pattern, or at least use only one static variable, namely the one holding the singleton object.
Please clarify my queries regarding Singleton and Multithreading:
What is the best way to implement Singleton in Java, in a multithreaded
environment?
What happens when multiple threads try to access getInstance()
method at the same time?
Can we make singleton's getInstance() synchronized?
Is synchronization really needed, when using Singleton classes?
Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:
Draconian synchronization:
private static YourObject instance;
public static synchronized YourObject getInstance() {
if (instance == null) {
instance = new YourObject();
}
return instance;
}
This solution requires that every thread be synchronized when in reality only the first few need to be.
Double check synchronization:
private static final Object lock = new Object();
private static volatile YourObject instance;
public static YourObject getInstance() {
YourObject r = instance;
if (r == null) {
synchronized (lock) { // While we were waiting for the lock, another
r = instance; // thread may have instantiated the object.
if (r == null) {
r = new YourObject();
instance = r;
}
}
}
return r;
}
This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.
Initialization on Demand:
private static class InstanceHolder {
private static final YourObject instance = new YourObject();
}
public static YourObject getInstance() {
return InstanceHolder.instance;
}
This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.
This pattern does a thread-safe lazy-initialization of the instance without explicit synchronization!
public class MySingleton {
private static class Loader {
static final MySingleton INSTANCE = new MySingleton();
}
private MySingleton () {}
public static MySingleton getInstance() {
return Loader.INSTANCE;
}
}
It works because it uses the class loader to do all the synchronization for you for free: The class MySingleton.Loader is first accessed inside the getInstance() method, so the Loader class loads when getInstance() is called for the first time. Further, the class loader guarantees that all static initialization is complete before you get access to the class - that's what gives you thread-safety.
It's like magic.
It's actually very similar to the enum pattern of Jhurtado, but I find the enum pattern an abuse of the enum concept (although it does work)
If you are working on a multithreaded environment in Java and need to gurantee all those threads are accessing a single instance of a class you can use an Enum. This will have the added advantage of helping you handle serialization.
public enum Singleton {
SINGLE;
public void myMethod(){
}
}
and then just have your threads use your instance like:
Singleton.SINGLE.myMethod();
Yes, you need to make getInstance() synchronized. If it's not there might arise a situation where multiple instances of the class can be made.
Consider the case where you have two threads that call getInstance() at the same time. Now imagine T1 executes just past the instance == null check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance() synchronized prevents this problem.
There a few ways to make singletons thread-safe, but making getInstance() synchronized is probably the simplest.
Enum singleton
The simplest way to implement a Singleton that is thread-safe is using an Enum
public enum SingletonEnum {
INSTANCE;
public void doSomething(){
System.out.println("This is a singleton");
}
}
This code works since the introduction of Enum in Java 1.5
Double checked locking
If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.
public class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance ;
}
}
This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.
Early loading Singleton (works even before Java 1.5)
This implementation instantiates the singleton when the class is loaded and provides thread safety.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
public void doSomething(){
System.out.println("This is a singleton");
}
}
You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.
public class MySingleton {
private static final MySingleton instance;
static {
instance = new MySingleton();
}
private MySingleton() {
}
public static MySingleton getInstance() {
return instance;
}
}
What is the best way to implement Singleton in Java, in a multithreaded environment?
Refer to this post for best way to implement Singleton.
What is an efficient way to implement a singleton pattern in Java?
What happens when multiple threads try to access getInstance() method at the same time?
It depends on the way you have implemented the method.If you use double locking without volatile variable, you may get partially constructed Singleton object.
Refer to this question for more details:
Why is volatile used in this example of double checked locking
Can we make singleton's getInstance() synchronized?
Is synchronization really needed, when using Singleton classes?
Not required if you implement the Singleton in below ways
static intitalization
enum
LazyInitalaization with Initialization-on-demand_holder_idiom
Refer to this question fore more details
Java Singleton Design Pattern : Questions
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis () {...}
}
Source : Effective Java -> Item 2
It suggests to use it, if you are sure that class will always remain singleton.
The classic of writing a singleton in java is like this:
public class SingletonObject
{
private SingletonObject()
{
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
private static SingletonObject ref;
}
and we can add synchronized keyword if we need it to run in multithreaded cases.
But I prefer to write it as:
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
return ref;
}
private static SingletonObject ref = new SingletonObject();
}
which I think is more concise, but strangely I didn't see any sample code written in this way, is there any bad effects if I wrote my code in this way?
The difference between your code and the "sample code" is that your singleton is instantiated when the class is loaded, while in the "sample" version, it is not instantiated until it is actually needed.
In the second form, your singleton is eagerly loaded and this is actually the preferred form (and the first one isn't thread-safe as you mentioned it yourself). Eager loading is not a bad thing for production code but there are contexts where you might want to lazy load your singletons, as discussed by the author of Guice, Bob Lee, in Lazy Loading Singletons that I'm quoting below:
First, why would you want to lazy load
a singleton? In production, you
typically want to eagerly load all
your singletons so you catch errors
early and take any performance hit up
front, but in tests and during
development, you only want to load
what you absolutely need so as not to
waste time.
Before Java 1.5, I lazy loaded
singletons using plain old
synchronization, simple but effective:
static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
Changes to the memory model in 1.5
enabled the infamous Double-Checked
Locking (DCL) idiom. To implement DCL,
you check a volatile field in the
common path and only synchronize when
necessary:
static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
But volatile isn't that much faster
than synchronized, synchronized is
pretty fast nowadays, and DCL requires
more code, so even after 1.5 came out,
I continued using plain old
synchronization.
Imagine my surprise today when Jeremy
Manson pointed me to the
Initialization on Demand Holder
(IODH) idiom which requires very
little code and has zero
synchronization overhead. Zero, as in
even faster than volatile. IODH
requires the same number of lines of
code as plain old synchronization, and
it's faster than DCL!
IODH utilizes lazy class
initialization. The JVM won't execute
a class's static initializer until you
actually touch something in the class.
This applies to static nested classes,
too. In the following example, the
JLS guarantees the JVM will not
initialize instance until someone
calls getInstance():
static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
[...]
Update: Credit where credit is due, Effective Java (copyright
2001) detailed this pattern under item
48. It goes on to point out that you still have to use synchronization or
DCL in non-static contexts.
I also switched singleton handling in
my framework from synchronization to
DCL and saw another 10% performance
boost (compared to before I started
using cglib's fast reflection). I only
used one thread in my micro-benchmark,
so the boost to concurrency could be
even greater given that I replaced a
heavily contended lock with a
relatively fine grained volatile field
access.
Note that Joshua Bloch now recommends (since Effective Java, 2nd ed) to implement singletons using a single-element enum as pointed out by Jonik.
Well, in the latter case the singleton object gets created before it is ever needed, but in most cases that's probably not horribly bad.
By the way, Joshua Bloch recommends (in Effective Java, 2nd ed, item 3) implementing singletons using a single-element enum:
public enum SingletonObject {
INSTANCE;
}
He gives the following justification:
[...] it is more concise, provides serialization
machinery for free, and provides an
ironclad guarantee against multiple
instantiation, even in the face of
sophisticated serialization or
reflection attacks. While this
approach has yet to be widely adopted,
a single-element enum type is the best
way to implement a singleton.
I would say the latter code is the more standard pattern, actually. Your first version isn't thread-safe. Ways of making it thread-safe include synchronizing on every access, or very carefully making it use double-checked locking (which is safe as of the Java 5 memory model, so long as you get it right).
Note that due to classes being initialized lazily, your latter code would still only create an object unnecessarily if you called static methods on the class without wanting to create the instance.
There's a pattern using a nested class to do the initialization which can make this lazier, but personally the second form almost always does well enough for me on its own.
There are more details of this in Effective Java, but I don't have it with me to find the item number, I'm afraid.
I think your problem is that you're mixing singleton and lazy initialization. A singleton can be implemented with different initialization strategies:
initialization on class loading
lazy initialization that uses double checked locking
lazy initialization with single checking (with possible repeated initialization)
lazy initialization that uses the class loader (holder class idiom)
All these approaches are discussed in Effective Java 2nd Item 71: Use lazy initialization judiciously.
the second way will solve multi-threading issue but will always create the Singleton even when you don't need it. The best way to do it is to create a Nested class.
public class singleton
{
private singleton()
{
System.out.println("I'am called only when it's needed");
}
static class Nested
{
Nested() {}
private static final singleton instance = new singleton();
}
public static singleton getInstance()
{
return Nested.instance;
}
public static void main(String [] args)
{
singleton.getInstance();
}
}
The best way to write a singleton class is given below .Please try it
public final class SingeltonTest {
/**
* #param args
* #return
*/
private static SingeltonTest instance = null;
private SingeltonTest() {
System.out.println("Rahul Tripathi");
}
public static SingeltonTest getInstance() {
if (instance == null) {
synchronized (SingeltonTest.class) {
if (instance == null)
instance == new SingeltonTest();
}
}
return instance;
}
}
Different ways to implement singleton pattern in java is as follows
public class SingletonClass {
private SingletonClass= null;
public static SingletonClass getInstance() {
if(SingletonClass != null) {
SingletonClass = new SingletonClass();
}
}
}
This is not thread safe. The following are thread safe implementation of singleton design pattern
1. Draconian synchronization
private static YourObject instance;
public static synchronized YourObject getInstance() {
if (instance == null) {
instance = new YourObject();
}
return instance;
}
2.Double check synchronization
Reference
private static final Object lock = new Object();
private static volatile YourObject instance;
public static YourObject getInstance() {
YourObject r = instance;
if (r == null) {
synchronized (lock) { // While we were waiting for the lock, another
r = instance; // thread may have instantiated the object.
if (r == null) {
r = new YourObject();
instance = r;
}
}
}
return r;
}
3. Initialization-on-demand holder idiom
Reference
public class Something {
private Something() {}
private static class LazyHolder {
static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
4. Other one is using enum
public enum Singleton {
SINGLE;
public void myMethod(){
}
}
// Lazy loading enabled as well as thread safe
class Singleton {
private static class SingletonHolder {
public static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
I am declaring private constructor and static block so the purpose of static block is it will execute only once and inside a static block I am creating an object so constructor will be invoked only once.
class Demo {
static Demo d=null;
static {
d=new Demo();
}
private Demo(){
System.out.println("Private Constructor");
}
void add(){
System.out.println("Hello I am Non-Static");
}
static Demo getInstance(){
return d;
}
}
I agree with Anon, and in the case where I always want to instantiate the singleton I would use
public class SingletonObject
{
public static SingletonObject REF = new SingletonObject();
private SingletonObject()
{
// no code req'd
}
}