I want to be sure that my Singleton instance is available safely and with minimum synchronization but I have doubt about the first if clause outside the synchronized block. Is it possible for the INSTANCE to have a not-null value when it isn't completely constructed? If so how can I solve the issue.
I think that including the whole get() block will reduce the efficiency because there will be so many configuration variables that must be read thousands of times per second from different part of program via this get() method.
public class ConfsDBLoader {
private static ConfsDBLoader INSTANCE = null;
private static final Object lock = new Object();
private ConfsDBLoader() { //Codes loading the db objects
}
public static ConfsDBLoader get(){
if(INSTANCE != null){
return INSTANCE;
} else {
synchronized(lock){
if(INSTANCE == null){
INSTANCE = new ConfsDBLoader();
}
return INSTANCE;
}
}
}
}
NOTE: I cant use static initialization because my hibernate sessionFactory is initialized statically and I want to have complex static structures that need each other. In fact I already have it and I'm not interested to make it more and more complex and investigate where these these static attributes try to use each other.
No. There is not enough synchronization to make sure that you are seeing the correct value on INSTANCE. You may see a non-null, but corrupt instance if your ConfsDBLoader because it may not be properly constructed by the time another thread calls getInstance().
You have 3 choices:
Eager initialize and make final
Synchronize whole method
Make INSTANCE volatile
Related
I've been wondering about singletons in Java. By convention, a singleton is set up something like this:
private static MyClass instance = null;
public static MyClass getInstance(){
if (instance == null){
instance = new MyClass();
}
return instance;
}
private MyClass(){}
Recently I've switched to using the following:
public static final MyClass instance = new MyClass();
private MyClass(){}
This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?
The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
lexically nested within T (§8.1.3) is executed. [...]
Invocation of certain reflective methods in class Class and in
package java.lang.reflect also causes class or interface initialization.
The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.
Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).
Note: the first version is not thread safe in the pasted snippet
The way you have first described is known as lazy instantiation, i.e the object will only be created when it is first called. This method is not thread-safe as it is possible for a second thread to create a second instance.
If you read the following book:
Effective Java by Joshua Bloch
He explains that the best implementation of the singleton pattern is through the use of an Enum :
public enum Singleton {
INSTANCE;
public void doSomething() {
...
}
}
Then you would call your singleton through the Enum as follows:
public class Test {
public void test(){
Singleton.INSTANCE.doSomething();
}
}
This fits nicely with what you are saying in terms of it looks nicer and shorter to write but also guarantees there can never be a second instance.
I can think of two reasons:
The first is Encapsulation: you might have second thoughts about how and when your singleton is initialized, after your class has been exposed to client code. And an initialization method gives you more freedom as to changing your strategy later on. For example you might change your mind and decide to use two different constructors instead of one, according to another static variable's value at runtime. With your solution you're bound to using just one constructor at the time your class is loaded into memory, whereas with getInstance() you can change the initialization logic without affecting the interface to the client code.
The second is Lazy Initialization : with the conventional singleton implementation the MyClass object is loaded into memory only when needed by the client code for the first time. And if the client code doesn't need it at all, you save on the memory allocated by your application. Note that whether your singleton is needed or not might not be certain until the program runs. For example it might depend on the user interaction with the program.
However the Lazy Initialization is not something you might necessarily want. For example if you're programming an interactive system and the initialization of your singleton is time consuming, it might actually be better to initialize it when the program is loading rather than when the user is already interacting with it, cause the latter might cause a latency in your system response the first time getInstance() is called. But in this case you can just have your instance initialized with the public method as in:
private static MyClass instance = getInstance();
The best way to synchronize the threads is using Double Checked (to ensure that only one thread will enter the synchronized block at a time and to avoid obtaining the lock every time the code is executed).
public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
// private attribute of this class
private String searchWord = "";
private String[] list = new String[]{"Stack", "Overflow"};
// private constructor
private SearchBox() {}
// static method to get instance
public static SearchBox getInstance() {
if (searchBox == null) { // first time lock
synchronized (SearchBox.class) {
if (searchBox == null) { // second time lock
searchBox = new SearchBox();
}
}
}
return searchBox;
}
}
Reflection: Reflection can be caused to destroy singleton
property of singleton class, as shown in following example:
// Java code to explain effect of Reflection
import java.lang.reflect.Constructor;
// Singleton class
class Singleton
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
public class GFG
{
public static void main(String[] args)
{
Singleton instance1 = Singleton.instance;
Singleton instance2 = null;
try
{
Constructor[] constructors =
Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors)
{
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance2 = (Singleton) constructor.newInstance();
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("instance1.hashCode():- "
+ instance1.hashCode()); //366712642
System.out.println("instance2.hashCode():- "
+ instance2.hashCode()); //1829164700
}
}
Here is my singleton class.
Static instance field is not volatile thus reordering/visibility problem arises. To solve it instance val field is made final. Since instance is properly constructed its clients should always see val field initialized if they see instance at all.
static class Singleton {
private static Singleton instance;
private final String val;
public Singleton() { this.val = "foo"; }
public static Singleton getInstance() {
if (instance == null)
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
return instance;
}
public String toString() { return "Singleton: " + val; }
}
However there is another problem - I've got two unprotected reads of "instance" field which can be(?) reordered so that client may get null instead of real value:
public static Singleton getInstance() {
Singleton temp = instance;
if (instance != null) return temp;
else { /* init singleton and return instance*/ }
}
To workaround this I feel like I can introduce local variable:
public static Singleton getInstance() {
Singleton temp = instance;
if (temp == null)
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
temp = instance;
}
}
return temp;
}
This seem to solve the problem since there is only one unprotected read of value so nothing really evil should happen. But... I've just modified the program flow without(almost?) changing its single threaded semantics. Does this mean that compiler can just undo my workaround since this transformation is safe and there is no way to make this code working without establishing proper happens-before relationship with volatile?
I’m not sure whether a reordering of reads of the same variable really may occur, but it’s guaranteed that local variables are unaffected by other thread’s activities. Even if such read reorderings do not happen, this guaranty is relevant for every variable which might be updated concurrently while you read it: if you read a value and store it into a local variable you can be sure that the value of the local variable does not suddenly change afterwards. Of course, if the value is a reference, that guaranty does not apply to the fields of the referenced object.
The relevant sentence can be found in the JLS §17.4.1:
Local variables (§14.4), formal method parameters (§8.4.1), and exception handler parameters (§14.20) are never shared between threads and are unaffected by the memory model.
So the answer is no, a compiler is not allowed to undo your workaround of introducing a local variable.
The safest way to do lazy-initialisation singletons is to use another class to hold the single instance field and rely on the guarantees the Java language provides for class initialisation
public class Singleton {
private static class Holder {
static final Singleton instance = new Singleton();
}
public Singleton getInstance() {
return Holder.instance;
}
}
The Holder class will only be initialised (and thus the instance created) the first time getInstance() is called.
I don't think you have an issue from the beginning.
You use synchronized(Singleton.class). Upon synchronized Java guarantees any read/write before this keyword are readily reflected into memory for involved variables. Since your Singleton instance is also declared at class level, any modification to it is readily visible from other class and is populated into main memory.
I'm seeking an answer to a question similar to Is it appropriate to use AtomicReference.compareAndSet to set a reference to the results of a database call? but with different requirement.
The goal is to create an instance of ObjectWithSideEffectConstructor only once to avoid duplicate side effects. The construction must happen in setUp(). Multiple threads will call setUp(). Similarly there will be a tearDown() for reclaiming the resource from the object, which is omitted here. Question: what is the best practice to achieve the goal?
Simply using AtomicReference will not be enough, because the constructor will be executed first, so as the side effect.
private static AtomicReference<ObjectWithSideEffectConstructor> ref =
new AtomicReference<ObjectWithSideEffectConstructor>()
void setUp() {
ref.compareAndSet(null, new ObjectWithSideEffectConstructor());
}
Using the answer from Is it appropriate to use AtomicReference.compareAndSet to set a reference to the results of a database call? will not work, because volatile lacks of synchronization. There will be window that multiple threads enters if.
private static volatile ObjectWithSideEffectConstructor obj;
void setUp() {
if (obj == null) obj = new ObjectWithSideEffectConstructor();
}
Simple fix would be
private static ObjectWithSideEffectConstructor obj;
private static final Object monitor = new Object();
void setUp() {
synchronized (monitor) {
if (obj == null) obj = new ObjectWithSideEffectConstructor();
}
}
Similarly, DCL with volatile monitor may give better read performance. But both requires some level of synchronization, thus expect worse performance.
Also we can use FutureTask. It is more efficient because once the object is created, subsequent FutureTask.get() will return without blocking. But it is definitely much more complicated than synchronized.
private static final AtomicReference<FutureTask<ObjectWithSideEffectConstructor>> ref =
new AtomicReference<FutureTask<ObjectWithSideEffectConstructor>>();
void setUp() {
final FutureTask<ObjectWithSideEffectConstructor> future =
new FutureTask<ObjectWithSideEffectConstructor>(
new Callable<ObjectWithSideEffectConstructor>() {
#Override
public ObjectWithSideEffectConstructor call() throws InterruptedException {
return new ObjectWithSideEffectConstructor();
}
}
);
if (ref.compareAndSet(null, future)) future.run();
ref.get().get();
}
Thanks for suggestions.
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 coding pattern is known as the Initialization-on-demand holder idiom. It 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.
Implementing Singleton in Java 5 or above version using Enum:
Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.
Let us see a simple implementation:
public enum SingletonEnum
{
INSTANCE;
public void doStuff()
{
System.out.println("Singleton using Enum");
}
}
// How to use in other classes
public static void main(String[] args)
{
SingletonEnum.INSTANCE.doStuff();
}
Always use the enum type for singletons, not only does it enforce the singleton elegantly, it also prevents common programming errors like when a singleton inherits a clone() method from its superclass and the programmer forgets to override it with a private method declaration. Or when you forget to override deserialisable, and allow programmers to serialise your singleton, declare a new instance, and then deserialise the old one.
Alternatively, if you use a static factory pattern, you can declare instance fields transient and use a readresolve method. This provides the flexibility if you might change your mind about whether it should be a singleton later in the design process.
Credit: Answer based on Effective Java by J Bloch (Item 3), a book every Java programmer should read, own and refer to regularly...
I assume you only want one ObjectWithSideEffectConstructor. There's a question here as to whether 1) it's the side effect happening twice your want to avoid, or 2) you just need to end up with a consistent (singleton) reference.
Either way, synchronized is a good standard option. It will keep other threads from constructing a second instance, while the first thread is in setup.
If you're in situation 1), using synchronized is probably required. If performance after startup were critical, you could possibly consider preceding the synchronized section with an AtomicReference.get() fast-path, to enable the synchronized section to be avoided after startup is complete.
If you're in situation 2), then -- it's not really clear from your question -- there is a side-effect of construction, but you don't care about duplicating that -- just so long as the client code only "sees" a consistent single reference.
In that second case, you could use AtomicReference.get() to check whether it's already initialized, and return if so. Threads would then enter the "race section" where they would construct (potentially multiple) ObjectWithSideEffectConstructor. Lastly, there would be a compareAndSet so that only one thread set the singleton.. with failing threads falling back to anAtomicReference.get() to take the correct singleton.
Performancewise, a single call to AtomicReference is faster than a synchronized block -- but I'm not sure if, with the double- and triple-checking & construction of unwanted side-effect objects, the second approach would be. A simple synchronized block might, again, be simpler & faster.
I'd be interested to see some measurements.
The synchronized method would be the way to go. If you actually need the performance you need to restructure your code to have a single-threaded pre-initialization. Using any other form will cause side-effects as described in the singleton pattern.
For what it's worth, the FutureTask approach doesn't actually require all of that code; the AtomicReference is not needed, and there shouldn't be any need to call both run() and get(). So you can simplify it slightly:
private static final Future<ObjectWithSideEffectConstructor> future =
new FutureTask<>(
new Callable<ObjectWithSideEffectConstructor>() {
#Override
public ObjectWithSideEffectConstructor call() throws InterruptedException {
return new ObjectWithSideEffectConstructor();
}
}
);
void setUp() {
future.run(); // or future.get(), if you want to get any exception immediately
}
Furthermore, with Java 8, the initialization expression can be written much more briefly; the above can be reduced to just:
private static final Future<ObjectWithSideEffectConstructor> future =
new FutureTask<>(ObjectWithSideEffectConstructor::new);
void setUp() {
future.run(); // or future.get(), if you want to get any exception immediately
}
This question already has answers here:
Why is volatile used in double checked locking
(8 answers)
Closed 5 years ago.
private volatile static Singleton uniqueInstance
In a singleton when using double lock method for synchronization why is the single instance declared as volatile ? Can I achieve the same functionality without declaring it as volatile ?
The volatile prevents memory writes from being re-ordered, making it impossible for other threads to read uninitialized fields of your singleton through the singleton's pointer.
Consider this situation: thread A discovers that uniqueInstance == null, locks, confirms that it's still null, and calls singleton's constructor. The constructor makes a write into member XYZ inside Singleton, and returns. Thread A now writes the reference to the newly created singleton into uniqueInstance, and gets ready to release its lock.
Just as thread A gets ready to release its lock, thread B comes along, and discovers that uniqueInstance is not null. Thread B accesses uniqueInstance.XYZ thinking that it has been initialized, but because the CPU has reordered writes, the data that thread A has written into XYZ has not been made visible to thread B. Therefore, thread B sees an incorrect value inside XYZ, which is wrong.
When you mark uniqueInstance volatile, a memory barrier is inserted. All writes initiated prior to that of uniqueInstance will be completed before the uniqueInstance is modified, preventing the reordering situation described above.
Without volatile the code doesn't work correctly with multiple threads.
From Wikipedia's Double-checked locking:
As of J2SE 5.0, this problem has been fixed. The volatile keyword now ensures that multiple threads handle the singleton instance correctly. This new idiom is described in The "Double-Checked Locking is Broken" Declaration:
// Works with acquire/release semantics for volatile
// Broken under Java 1.4 and earlier semantics for volatile
class Foo {
private volatile Helper helper = null;
public Helper getHelper() {
Helper result = helper;
if (result == null) {
synchronized(this) {
result = helper;
if (result == null) {
helper = result = new Helper();
}
}
}
return result;
}
// other functions and members...
}
In general you should avoid double-check locking if possible, as it is difficult to get right and if you get it wrong it can be difficult to find the error. Try this simpler approach instead:
If the helper object is static (one per class loader), an alternative is the initialization on demand holder idiom
// Correct lazy initialization in Java
#ThreadSafe
class Foo {
private static class HelperHolder {
public static Helper helper = new Helper();
}
public static Helper getHelper() {
return HelperHolder.helper;
}
}
To avoid using double locking, or volatile I use the follow
enum Singleton {
INSTANCE;
}
Creating the instance is simple, lazy loaded and thread safe.
Write to a volatile field will happen before any read operation.
Below is an example code for better understanding:
private static volatile ResourceService resourceInstance;
//lazy Initialiaztion
public static ResourceService getInstance () {
if (resourceInstance == null) { // first check
synchronized(ResourceService.class) {
if (resourceInstance == null) { // double check
// creating instance of ResourceService for only one time
resourceInstance = new ResourceService ();
}
}
}
return resourceInstance;
}
This link can serve you better
http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html
You can use the follow code:
private static Singleton uniqueInstance;
public static synchronized Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance
}
I am going through Java Memory Model video presentation and author is saying it is better to use Static Lazy Initialization compared to Lazy Initialization and I do not clear understand what he wants to say.
I wanted to reach to community and would appreciate if someone can explain difference between Static Lazy Initialization and Lazy Initialization with simple java code example.
Reference: Advanced Programming Topics - Java Memory Model
Well both implementations can be static so that is the first misunderstanding. The presenter in this video is explaining how you can exploit the thread-safety of class initialization.
Class initialization is inherently thread-safe and if you can have an object initialized on class initialization the object creation too are thread-safe.
Here is an example of a thread-safe statically initialized object
public class MySingletonClass{
private MySingletonClass(){
}
public static MySingletonClass getInstance(){
return IntiailizationOnDemandClassholder.instance;
}
private static class IntiailizationOnDemandClassHolder{
private static final MySingletonClass instance = new MySingletonClass();
}
}
What is important to know here, MySingletonClass instance variable will never be created and or initialized until getInstance() is invoked. And again since class initialization is thread-safe the instance variable of IntiailizationOnDemandClassholder will be loaded safely, once and is visible to all threads.
To answer your edit depends on your other type of implementation. If you want to do double-checked-locking your instance variable would need to be volatile. If you do not want DCL then you will need to synchronize access each time to your variable. Here are the two examples:
public class DCLLazySingleton{
private static volatile DCLLazySingleton instance;
public static DCLLazySingleton getInstace(){
if(instance == null){
synchronized(DCLLazySingleton.class){
if(instance == null)
instance=new DCLLazySingleton();
}
}
return instance;
}
and
public class ThreadSafeLazySingleton{
private static ThreadSafeLazySingleton instance;
public static ThreadSafeLazySingleton getInstance(){
synchronized(ThreadSafeLazySingleton.class){
if(instance == null){
instance = new ThreadSafeLazySingleton();
}
return instance;
}
}
The last example requires a lock acquisition on every request of the instance. The second example requires a volatile-read on each access (may be cheap or not, depends on the CPU).
The first example will always lock once regardless of the CPU. Not only that but each read will be a normal without any need to worry about thread-safety. I personally like the first example I have listed.
I think the author in the presentation refers to the fact that a static field would be initialized only once in a thread-safe way at the first use of the class which contains that field (this is guaranteed by JMM):
class StaticLazyExample1 {
static Helper helper = new Helper();
static Helper getHelper() {
return helper;
}
}
Here helper field would be initialized upon first usage of StaticLazyExample1 class (i.e. upon constructor or static method call)
There is also Initialization On Demand Holder idiom, which is based on static lazy initialization:
class StaticLazyExample2 {
private static class LazyHolder {
public static Helper instance = new Helper();
}
public static Helper getHelper() {
return LazyHolder.instance;
}
}
Here a Helper instance would be created only upon first call to StaticLazyExample2.getHelper() static method. This code is guaranteed to be thread-safe and correct because of the initialization guarantees for static fields; if a field is set in a static initializer, it is guaranteed to be made visible, correctly, to any thread that accesses that class.
UPDATE
What is the difference between both types of initialization?
The static lazy initialization provides efficient thread safe lazy initialization of the static fields and has zero synchronization overhead.
On the other hand if you would like to lazily initialize a non-static field, you should write something like this:
class LazyInitExample1 {
private Helper instance;
public synchronized Helper getHelper() {
if (instance == null) instance == new Helper();
return instance;
}
}
Or use Double-Cheked Locking idiom:
class LazyInitExample2 {
private volatile Helper helper;
public Helper getHelper() {
if (helper == null) {
synchronized (this) {
if (helper == null) helper = new Helper();
}
}
return helper;
}
}
Should I mention they both require explicit synchronization and carry additional timing overhead comparing to static lazy initialization?
It is worth noting that the simplest thread safe static lazy initialisation is to use an enum This works because initialisation of static fields is thread safe and classes are lazily loaded anyway.
enum ThreadSafeLazyLoadedSingleton {
INSTANCE;
}
A class which uses a lazy loaded value is String. The hashCode is only computed the first time it is used. After that the cached hashCode is used.
I don't think you can say that one is better than the other because they are not really interchangeable.
A reference would be good here, for sure. They both have the same basic idea: Why allocate resources (memory, cpu) if you don't have to? Instead, defer allocation of those resources until they're actually needed. This can be good in intensive environments to avoid waste, but can be very bad if you need the results right now and cannot wait. Adding a "lazy but prudent" system is very difficult (one that detects downtime and runs these lazy calculations when it gets free time.)
Here's an example of lazy initialization.
class Lazy {
String value;
int computed;
Lazy(String s) { this.value = s; }
int compute() {
if(computed == 0) computed = value.length();
return computed;
}
}
Here's static lazy initializtion
class StaticLazy {
private StaticLazy staticLazy;
static StaticLazy getInstance() {
if(staticLazy == null) staticLazy = new StaticLazy();
return staticLazy;
}
}
The distinction is the mechanism you implement the lazy initialization. By Static Lazy Initialization I assume the presenter means this solution which relies on the JVM being compliant with any version of Java (see 12.4 Initialization of Classes and Interfaces, of the Java Language Specification).
Lazy Initialization probably means lazy initialization described in many other answers to this question. Such initialization mechanisms make assumptions about the JVM that are not thread-safe until Java 5 (as Java 5 has a real memory model specification).
Lazy loading is just a fancy name given to the process of initializing a class when it’s actually needed.
In simple words, Lazy loading is a software design pattern where the initialization of an object occurs only when it is actually needed and not before to preserve simplicity of usage and improve performance.
Lazy loading is essential when the cost of object creation is very high and the use of the object is very rare. So this is the scenario where it’s worth implementing lazy loading.The fundamental idea of lazy loading is to load object/data when needed.
Source: https://www.geeksforgeeks.org/lazy-loading-design-pattern/