Scale up as you grow — whether you're running one virtual machine or ten thousand.

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.

Example 3 is the traditional double check idiom for lazy initialization. The double check is badly broken in java before version 5. The example you have here is broken also because instance is not declared volatile. The best way is to extract the singleton code to a separate class which is guaranteed to be loaded only when the referring class is instantiated. For more information see item 71 in “Effective Java” (2nd edition) by Joshua Bloch. But you’d better avoid singletons completely.
- Erik van Oosten
you can avoid your extra if condition if you create instance described below, Once we declare static, it will refer the same object all the time package com.journaldev.designpatterns; public class ASingleton{ private static ASingleton instance= new ASingleton(); private ASingleton(){ } public static synchronized ASingleton getInstance(){ return instance; } }
- Ben
',~ I am really thankful to this topic because it really gives useful information :-`
- Anonymous
double check lock is not thread safe in java this issue listed by PDM tool (block synchronizing)
- Hesham
there is a good way to implement the Singletons, that will look after all the issue and with lesser code public enum InputValidatorImpl { instance; // add some method }
- Rishi Dev Gupta
Hi Pankaj, I believe this is the best way, it doesn’t use any synchronization at all, provides better performance too. https://en.wikipedia.org/wiki/Initialization-on-demand\_holder\_idiom
- Asanka
String is not a very good candidate to be used in synchronization, so I have updated it with Object, learn more about synchronization and thread safety in java Why string is not good candidate… Since its immutable its a good candidate to use in synchronization block right.
- Naveen J
In your third approach, although it checks the value of instance once again within the synchronized block but the JIT compiler can rearrange the bytecode in a way that the reference to instance is set before the constructor has finished its execution. This means the method getInstance() returns an object that may not have been initialized completely. I think, the keyword volatile can be used for the instance variable. Variables that are marked as volatile get only visible to other threads once the constructor of the object has finished its execution completely.
- Archna Sharma
I think making instance volatile make much difference than approach given in post
- Amey Jadiye