Java Singleton with an inner class - what guarantees thread safety? - java

One common (1,2) way of implementing a singleton uses an inner class with a static member:
public class Singleton {
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private Singleton() {
//...
}
}
This implementation is said to be lazily initialized and thread-safe. But what exactly guarantees its thread safety? JLS 17 that deals with Threads and Locks doesn't mention that static fields have any sort of happens-before relationship. How can I be sure that the initialization will only happen once and that all threads see the same instance?

It's well described in Java Concurrency in Practice:
The lazy initialization holder class idiom uses a class whose only purpose is to initialize the Resource. The JVM defers initializing the ResourceHolder class until it is
actually used [JLS 12.4.1], and because the Resource is initialized
with a static initializer, no additional synchronization is needed.
The first call to getresource by any thread causes ResourceHolder to
be loaded and initialized, at which time the initialization of the
Resource happens through the static initializer.
Static initialization
Static initializers are run by the JVM at class initialization time,
after class loading but before the class is used by any thread.
Because the JVM acquires a lock during initialization [JLS 12.4.2] and
this lock is acquired by each thread at least once to ensure that the
class has been loaded, memory writes made during static initialization
are automatically visible to all threads. Thus statically initialized
objects require no explicit synchronization either during construction
or when being referenced.

There are two points we need to understand first:
Static initialization happens only once when loading the class
Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory
....
Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class
This means that static initializers executed only once when initializing the object class (the actual Class object , not an instance of the class).
Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time.
For each class or interface C, there is a unique initialization lock LC. The mapping from C to LC is left to the discretion of the Java Virtual Machine implementation.
Now, in simple words, when two threads try to initialize instance the first thread which acquire LC is the one that actually initialize instnace, and because it does that statically, java provides a promise that it happens only once.
For more information regarding initialization lock read JSL 17

Related

Singleton in enum performance

I was wondering about singleton in enum and it's performance.
When we have multithreaded environment we have to synchronize moment, when an instance is created.
Simply, we can use synchronized mod, for function called getInstance() which create instance
Somethink like that:
public synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
It's lazy implementation it's good for me. But synchronized method is slow.
We can use double-locking to make it faster.
How about enum?
When we implement singleton as enum, instance of singleton will be created as first use. Next use, return current instance.
How it works?
When we want to get existing instance, there is implicit synchronized method which are slow? Or there is Double-lock implemented?
Enum is thread-safe and is also the recommended way to implement a Singleton.
That said, enum is not lazily loaded. If you want a lazy-loaded singleton, you can use the Holder pattern (which is thread-safe as well):
class LazySingleton {
private LazySingleton() {}
private static class SingletonHelper{
private static final LazySingleton INSTANCE = new LazySingleton();
}
public static LazySingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
There is no lazy initialization with an enum. It will simply create the instance when the class is loaded.
When we implement singleton as enum, instance of singleton will be created as first use.
That is only true if by "first use" you actually mean "when the class is loaded".
In other words, using your example, an enum would be equivalent to:
private static final Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
The initialization of enum constants happens in the class initializer, similar to had you written
static final Singleton instance = new Singleton();
or
static final Singleton instance;
static {
instance = new Singleton();
}
The safety comes from the fact that the JVM perform class initialization under a JVM specific lock:
Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. … The implementation of the Java Virtual Machine is responsible for taking care of synchronization and recursive initialization by using the following procedure.
…
For each class or interface C, there is a unique initialization lock LC. The mapping from C to LC is left to the discretion of the Java Virtual Machine implementation.
…
I left out a lot of technical details from the specification, as to a Java programmer, the most important point is that there is a safety mechanism implemented by every conforming JVM. The end of the section has the comment:
An implementation may optimize this procedure by eliding the lock acquisition in step 1 (and release in step 4/5) when it can determine that the initialization of the class has already completed, provided that, in terms of the memory model, all happens-before orderings that would exist if the lock were acquired, still exist when the optimization is performed.
This is, of course, an important point of this implementation of the singleton pattern, that later access to the static final field does not need to acquire a lock. Since all classes go from the uninitialized to the initialized state exactly once and it affects every operation (including all other possibilities to implement the singleton pattern), you can expect every JVM to do this fundamental optimization. Even if a particular JVM does not do this, the static final field would be the fastest lazy singleton implementation on that virtual machine…

The instantiation happened before getInstance() or when getInstance()?

I'm following this tutorial for create Singleton and the owner have comment when the method below http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
If your singleton class is not using a lot of resources, this is the
approach to use. But in most of the scenarios, Singleton classes are
created for resources such as File System, Database connections etc
and we should avoid the instantiation until unless client calls the
getInstance method.
The Problem Is:
They say we should avoid the instantiation until unless client calls the getInstance method
BUT as I know in this code the instantiation (of object instance) always happened when class EagerInitializedSingleton load, and EagerInitializedSingleton just only load when we call EagerInitializedSingleton.getInstance()
=> The instantiation will happened on time with getInstance() and never before getInstance()
Reference:
Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
(from https://stackoverflow.com/a/8704607/5381331)
So when are classes loaded?
There are exactly two cases:
- when the new bytecode is executed (for example, FooClass f = new FooClass();)
- and when the bytecodes make a static reference to a class (for example, System.out)
(from http://www.javaworld.com/article/2077260/learn-java/learn-java-the-basics-of-java-class-loaders.html)
Am I wrong or correct. Please give me some sugestion.
In this case with that specific code, you are probably correct.
However, if you had static methods of EagerInitializedSingleton, or static non-final members of EagerInitializedSingleton referenced somewhere in your code base prior to the invocation of getInstance, the instance variable of EagerInitializedSingleton would initialize.
Same with a reflective invocation of Class.forName on your EagerInitializedSingleton class.
Note (and forgive the obvious here) that there are alternative ways of declaring a singleton, including lazy-initialization or enums.
I think the problem is when a class gets loaded without the need to get the instance, but for some other reason. You assume that class will be used the first time when user will want to get an instance of that singleton, but it may happen for some other reason, he may just call a class loader for something, or use some 3rd party software to validate a class, anything that comes to mind that involves loading a class but not getting an instance of a singleton.
They say we should avoid the instantiation until unless client calls
the getInstance method
The solution is lazy loading.
From wikipedia, Initialization-on-demand holder idiom
When the class Something is loaded by the JVM, the class goes through
initialization. Since the class does not have any static variables to
initialize, the initialization completes trivially. The static class
definition LazyHolder within it is not initialized until the JVM
determines that LazyHolder must be executed. The static class
LazyHolder is only executed when the static method getInstance is
invoked on the class Something, and the first time this happens the
JVM will load and initialize the LazyHolder class.
public class Something {
private Something() {}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}

singleton thread safety in Java

Basically i was going trough a multithreading guide in developers.android.com when i saw something that confused me...(i am reffering to this article
http://developer.android.com/training/multiple-threads/create-threadpool.html
)
In the Define the Thread Pool Class section where they mention that the class should have a private constructor in order to make it singleton, the writer claims that by doing this the code would not require synhronization. I am confused why this is thread safe, as altough it is a singleton it can still be referenced by multiple threads simultaneously causing memory consistency errors etc.
What they mean is:
Since the constructor is private only a method inside the class itself may create an instance of that class
The only instance of that class created is through:
static
{
// Creates a single static instance of PhotoManager
sInstance = new PhotoManager();
}
The static { ... } block is thread safe because it is executed by the class loader, which is synchronized

Static synchronized methods

I understand that Java instance synchronized methods can run parallel and the static ones will serialize the methods; my lack of understanding is, since the static method locks the Class object, what happens with other Class objects; are we locking between all static classes?
thanks.
Instead of taking the lock on the instance/object you are taking it on the class it self.
When you lock the class you are only locking that class, not all classes.
From the docs
A synchronized method acquires a monitor (§17.1) before it executes.
For a class (static) method, the monitor associated with the Class object for the method's class is used.
For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
Java classes have a monitor associated with the class instance. Since there is only one class instance per class the lock will only be acquired on that class instance.
Now each class defined has its own instance and thus its own monitor, so to answer your question: Synchronizing a static method will only block access to that class.

Is static inner class thread safe inside another java class?

For collection of smaller helper utility classes, I have created a general class MyUtils:
// MyUtils.java
public final class MyUtils
{
public static class Helper1 {};
public static class Helper2 {};
//...
}
This helper classes from inside MyUtils will be used in the other files of the package:
// MyClass1.java
public class MyClass1
{
private MyUtils.Helper1 help1 = new MyUtils.Helper1();
public void method ()
{
private MyUtils.Helper2 help2 = new MyUtils.Helper2();
}
}
To let them accessible, I have made them static inside MyUtils (which doesn't have any data/function member of its own). My code is thread safe before creating MyUtils.
My worry is, by making these inner classes staticwill they remain thread safe, when their multiple instances will exist across the files ? Or is their any bad implication am I missing due to making them static ?
Edit: I am not touching any shared variable inside the helper classes. My only concern was that will the instance of the static classes be thread safe (since they are static).
If you're asking whether these is any bad implication of going from:
public class Helper1 {}
...to:
public class MyUtils {
public static class Helper1 {}
}
Then no, there is not. The static keyword in this case is just "promoting" the nested inner class to a top-level class, so that you can instantiate it without needing an enclosing instance of MyUtils. Here is a passable article on the subject:
http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html
In essence, doing public static class X on a nested inner-class is the same as doing public class X in a standard top-level class.
There is no meaning to a "class" itself being thread-safe or not thread safe. Therefore, whether or not it is static is irrelevant.
When someone refers to a class being thread-safe or not thread-safe, they really mean that the functionalities provided by that class are thread-safe or not. Accordingly, it's what the inner classes do themselves that actually makes the difference.
There's nothing inherent about methods that make them unsafe to be reentrant. Problems arise when you start accessing shared variables, etc. So, for example, a member of the class accessed by the methods needs to be synchronized appropriately. But if the methods don't store any state, etc., then there's nothing stopping you from using them across multiple threads.
Hope that helps.
You will need to guard the access to help1 since this is an instance level (shared) variable.
While help2 is safe if you dont allow it to skip the method.
There is nothing special about the static classes and instance created out of it.
Same rules of thread safety applies to instances of static classes also which applies to normal cases.
static methods and inner classes don't have any access to the variables of their dynamic counter part, and consequently can't use monitors/synchronize on an instance of their parent class. Of course this doesn't mean that declaring them and using them is inherently non-thread safe. It's just that if you need to synchronize any of those static methods on an instance of the parent class, then you need to be sure that you synchronize/lock before entering them or else you must explicitly pass a reference to a parent instance into them.
I have got the answer. Making MyUtils an interface is more cleaner design, as I can get away with the static identifienr from the helper classes

Categories