Using volatile keyword for creating one instance - java

I have the following code:
public class EntityManagerFactoryProviderImpl implements EntityManagerFactoryProvider {
private EntityManagerFactory entityManagerFactory=null;//line XXX
public EntityManagerFactory getFactory(){
if (entityManagerFactory==null){
buildFactory();
}
return entityManagerFactory;
}
private synchronized void buildFactory(){
if (entityManagerFactory!=null){
return;
}
entityManagerFactory=...
}
}
So I need that entityManagerFactory instance was created only once - when getFactory() is first called.
Must I set variable entityManagerFactory on line XXX as volatile this case?
Also, EntityManagerFactoryProviderImpl is an OSGI Singleton Declarative Service, so there is always only one instance of this class.

There are theoretical possibilities that multiple threads are calling the code in parallel; and due to not using volatile, thread A doesn't see updates that thread B made.I have never encountered such behavior myself, but surr: it is possible and when it happens, very strange bugs might come out of having two instances of the same singleton.
You can study this SEI cert site for a full discussion of the subject.

I cannot see why you need to make this volatile. You use the double checked locking solution in your example. The link in the accepted answer also indicates this is compliant.
So the accepted answer is actually wrong, you do not need volatile. Howeer, the cleanest solution for this kind of initialization is the "initialize-on-Demand Holder Class Idiom" which is also at the link.
Update I was wrong. The double check locking can fail because the EntityManagerFactory object can be seen in a partially constructed state, only final fields in this objects are guaranteed to be seen. This is explicitly mentioned in http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5-110
int j = f.y; // could see 0
The "initialize-on-Demand Holder Class Idiom" is fastest.

The code in question isn't threadsafe because it has a check then act problem in the public method. The reason for this problem is that shared mutable state isn't properly syncrhonized in the class. Here's a solution:
public class EntityManagerFactory implements ....{
private static class EntityManagerHolder {
public static EntityManager entityManager = new EntityManager();
}
public static EntityManager getEntityManager(){
return EntityManagerHolder.entityManager;
}
}
Notice that there's no synchronized keyword here. This is because entityManager is initialized as static in the holder class which means it's loaded after class loading but before any threads can start and hence no synchrnonization is needed.
The sole purpose of the holder class is to prevent an eager initialization cost by using the JVM lazy class loading strategy. The holder class is only initialized when it's actually needed rather than at class load time with an eager static initialization.
Bottomline: You avoid synchronized and eager initialization and get a singleton all in one fell swoop. ;)

Related

Multithreaded Singleton

I have read about many possible ways to create a singleton for the multithreaded environment in Java, like Enums, Double-check locking, etc.
I found a simple way that is also working fine and I unable to find its drawbacks or failure cases. May anyone explain when it may fail or why we should not choose this approach.
public final class MySingleton {
public final static MySingleton INSTANCE = new MySingleton();
private MySingleton(){}
}
I am testing it with the below code and working fine:
public class MyThread {
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
Thread thread = new Thread(() -> {
MySingleton singleton = MySingleton.INSTANCE;
System.out.println(singleton.hashCode() + " " + Thread.currentThread().getName());
});
thread.start();
}
}
}
Every comment is appreciated.
Your singleton is instantiated when the class is loaded, therefore when the main method is started, it is already instantiated and from a multithreading perspective is safe.
But there are some arguments why this might not be the best approach:
When instantiating your singleton throws an exception, you get a nasty classloading exception which is hard to analyze, especially when you don't have a debugger to attach.
When instantiating takes some time, so you might don't want to do this when the class is loaded in order to minimize the startup time of your application
And additionally using singletons is not a good design as you hardcode the dependency between the client (that uses this class) and the implementation of this class. So it is hard to replace your implementation with a mock for testing.
Yes, this is a fine implementation of a singleton.
The test shows... something; but it doesn't really explain whether it's working or not. What you are trying to show (that only one instance is created) is essentially impossible to show with a test, because it's something that's guaranteed by the language spec.
See JLS 12, in particular JLS 12.4, which describes how classes are initialized.
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. The procedure for initializing C is then as follows:
Synchronize on the initialization lock, LC, for C. This involves waiting until the current thread can acquire LC.
If the Class object for C indicates that initialization is in progress for C by some other thread, then release LC and block the current thread until informed that the in-progress initialization has completed, at which time repeat this step.
If the Class object for C indicates that initialization is in progress for C by the current thread, then this must be a recursive request for initialization. Release LC and complete normally.
If the Class object for C indicates that C has already been initialized, then no further action is required. Release LC and complete normally.
...
So, classes are guaranteed to only be initialized once (if at all), because the initialization is done whilst holding a class-specific lock; the happens-before guarantees of acquiring and releasing that lock mean that the values of final fields are visible; so the INSTANCE field is guaranteed to be initialized once, and thus there is only one instance of MySingleton possible.
Note that your implementation is effectively the same as an enum:
public enum MySingleton {
INSTANCE
}
Enums are really just syntactic sugar for classes. If you decompiled an enum class, it would look something like:
public class MySingleton {
public static final MySingleton INSTANCE = new MySingleton(0);
private MySingleton(int ordinal) { ... }
}
It is perfectly fine and simple. Although you may check the trade offs listed below:
May lead to resource wastage. Because instance of class is created always, whether it is required or not.
CPU time is also wasted for creating the instance if it is not required.
Exception handling is not possible.
Also you have to be sure that MySingleton class is thread-safe
See
Java Singleton Design Pattern Practices with Examples
Ah, I ran into some problems using exactly this approach a few months ago. Most people here will tell you this is fine, and they are mostly right, as long as you know the constructor won't throw an exception. What I'm about to describe is a common but unpredictable artifact of JVM caching conventions.
I had a singleton that was set up exactly the one you show in your question. Every time I attempted to run the program I got a NoClassDefFoundError. I had no idea what was going wrong until I found this post on Reddit, aptly titled Using static initialization for singletons is bad!
Just FYI, if you initialize a singleton with static initialization, e.g., private static final MyObject instance = new MyObject(); and there's business logic in your constructor, you can easily run into weird meta-errors, like NoClassDefFoundError. Even worse, it's unpredictable. Certain conditions, such as the OS, can change whether an error occurs or not. Static initialization also includes using a static block, "static{...}" , and using the enum singleton pattern.
The post also links to some Android docs about the cause of the problem.
The solution, which worked very well for me, is called double checked locking.
public class Example {
private static volatile Example SINGLETON = null;
private static final Object LOCK = new Object();
private Example() {
// ...do stuff...
}
public static Example getInstance() {
if (SINGLETON == null) {
synchronized (LOCK) {
if (SINGLETON == null) {
SINGLETON = new Example();
}
}
}
return SINGLETON;
}
}
For the most part, you can probably do it the simple way without problems. But, if your constructor contains enough business logic that you start getting NoClassDefFoundError, this slightly more complicated approach should fix it.

Is there any need to add volatile keyword to guarantee thread-safe singleton class in java?

According to this post, the thread-safe singleton class should look as below. But I'm wondering whether there's a need to add volatile keyword to static CrunchifySingleton instance variable. Since if the instance is created and stored in CPU cache, at which time it is not written back to main memory, meanwhile, another thread invoke on getInstance() method. Will it incur an inconsistency problem?
public class CrunchifySingleton {
private static CrunchifySingleton instance = null;
protected CrunchifySingleton() {
}
// Lazy Initialization
public static CrunchifySingleton getInstance() {
if (instance == null) {
synchronized (CrunchifySingleton.class) {
if (instance == null) {
instance = new CrunchifySingleton();
}
}
}
return instance;
}
}
I echo #duffymo's comment above: lazy singletons are nowhere near as useful as they initially appear.
However, if you absolutely must use a lazily-instantiated singleton, the lazy holder idiom is much a easier way to achieve thread safety:
public final class CrunchifySingleton {
private static class Holder {
private static final CrunchifySingleton INSTANCE = new CrunchifySingleton();
}
private CrunchifySingleton() {}
static CrunchifySingleton getInstance() { return Holder.INSTANCE; }
}
Also, note that to be truly singleton, the class needs to prohibit both instantiation and subclassing - the constructor needs to be private, and the class needs to be final, respectively.
Yep, if your Singleton instance is not volatile or even if it is volatile but you are using sufficiently old JVM, there's no ordering guarantees for the operations in which the line
instance = new CrunchifySingleton();
decomposes with regard to the volatile store.
The compiler can then reorder these operations so that your instance is not null (because memory has been allocated), but is still uninitialized (because its constructor still hasn't been executed).
If you want to read more about the hidden problems around Double-Checked Locking, specifically in Java, see The "Double-Checked Locking is Broken" Declaration.
The lazy holder idiom is a nice pattern that generalizes well for general static field lazy loading, but if you need a safe and simple Singleton pattern, I'd recommend what Josh Bloch (from Effective Java fame) recommends - the Java Enum Singleton:
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
The code how you quoted it is broken in Java. Yes, you need volatile and at least Java 5 to make the double-checked idiom thread safe. And you should also add a local variable in your lazy initialization to improve performance. Read more about it here: https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
Yes, making volatile will gaurantee that every time any thread is trying to access your critical section of code, the thread reads the data from memory itself and not from hread cache.
You need volatile in this case but a better option is to use either an enum if it is stateless
enum Singleton {
INSTANCE;
}
however stateful singletons should be avoid every possible. I suggest you try creating an instance which you pass via dependency injection.

EnityManagerFactory Singleton. Please just check out?

I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerFactorySingleton {
private static EntityManagerFactorySingleton singleton;
private EntityManagerFactory emf;
public EntityManagerFactorySingleton(){
emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}
public synchronized static EntityManagerFactorySingleton getInstance() {
if(singleton == null) {
singleton = new EntityManagerFactorySingleton();
}
return singleton;
}
public EntityManagerFactory getEntityManagerFactory(){
return emf;
}
}
Your code is not "solid":
constructor must be private for a singleton
you shouldn't have the getInstance() method synchronised, although you need to perform the initialisation thread-safe. That's because after initialization, all the threads that need the instance will have to wait for each other (and that's a useless bottleneck).
Only if your instance is null, call a synchronized (private) method that performs the initialisation; inside that method, check again if the instance is null. Another approach is to have a private inner class SingletonHolder that holds the instance, so you'll rely on the class-loader for performing the thread-safe initialisation.
However, if you can't (don't want to) avoid using a singleton, a very good choice would be an enum with only one constant defined: INSTANCE;
public enum EntityManagerFactorySingleton {
INSTANCE;
// all your code -- fields, constructor, instance / static methods get in here
// you can still have the `getInstance()` static method returning INSTANCE, if you want.
}
The only drawback is that you cannot perform lazy initialisation for the INSTANCE, but you're now thread-safe and ready for serialization or cloning issues without any effort.
To answer your question - I think you should make the constructor private, to ensure other Classes cannot instantiate another EntityManagerFactorySingleton. However, if that is not happening, then I can see no reason why this class would be causing a pooling issue.
The code is not thread safe. (Sorry, missed the synchronized)
You should not use singletons.
Instead, use a DI framework like Spring, guice or maybe your deployment envionment already offers one.
This will make your code much more robust and much more simple to test.

Does Java have the static order initialisation fiasco?

A recent question here had the following code (well, similar to this) to implement a singleton without synchronisation.
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Now, I think understand what this is doing. Since the instance is static final, it's built long before any threads will call getInstance() so there's no real need for synchronisation.
Synchronisation would be needed only if two threads tried to call getInstance() at the same time (and that method did construction on first call rather than at "static final" time).
My question is therefore basically: why then would you ever prefer lazy construction of the singleton with something like:
public class Singleton {
private Singleton() {}
private static Singleton instance = null;
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
My only thoughts were that using the static final method may introduce sequencing issue as in the C++ static initialisation order fiasco.
First off, does Java actually have this problem? I know order within a class is fully specified but does it somehow guarantee consistent order between classes (such as with a class loader)?
Secondly, if the order is consistent, why would the lazy construction option ever be advantageous?
Now, I think understand what this is doing. Since the instance is static final, it's built long before any threads will call getInstance() so there's no real need for synchronisation.
Not quite. It is built when the SingletonHolder class is initialized which happens the first time getInstance is called. The classloader has a separate locking mechanism, but after a class is loaded, no further locking is needed so this scheme does just enough locking to prevent multiple instantiation.
First off, does Java actually have this problem? I know order within a class is fully specified but does it somehow guarantee consistent order between classes (such as with a class loader)?
Java does have a problem where a class initialization cycle can lead to some class observing another class's static finals before they are initialized (technically before all static initializer blocks have run).
Consider
class A {
static final int X = B.Y;
// Call to Math.min defeats constant inlining
static final int Y = Math.min(42, 43);
}
class B {
static final int X = A.Y;
static final int Y = Math.min(42, 43);
}
public class C {
public static void main(String[] argv) {
System.err.println("A.X=" + A.X + ", A.Y=" + A.Y);
System.err.println("B.X=" + B.X + ", B.Y=" + B.Y);
}
}
Running C prints
A.X=42, A.Y=42
B.X=0, B.Y=42
But in the idiom you posted, there is no cycle between the helper and the singleton so there is no reason to prefer lazy initialization.
Now, I think understand what this is
doing. Since the instance is static
final, it's built long before any
threads will call getInstance() so
there's no real need for
synchronisation.
No. SingletonHolder class will be loaded only when you invoke SingletonHolder.INSTANCE for the very first time. final Object will become visible to other threads only after it is fully constructed. Such lazy initialization is called Initialization on demand holder idiom.
In Effective Java, Joshua Bloch notes that "This idiom … exploits the guarantee that a class will not be initialized until it is used [JLS, 12.4.1]."
The patern that you described works for two reasons
Class is loaded and initialized when first accessed (via SingletonHolder.INSTANCE here)
Class loading and initialization is atomic in Java
So you do perform lazy initialization in a thread safe and efficient way. This pattern is better alternative to double lock (not working) solution to synchronized lazy init.
You initialize eagerly because you don't have to write a synchronized block or method. This is mainly because synchronization is generally considered expensive
Just a little note about the first implementation: the interesting thing here is that class initialization is used to replace classical synchronization.
Class initialization is very well defined in that no code can ever get access to anything of the class unless it is fully initialized (i.e. all static initializer code has run). And since an already loaded class can be accessed with about zero overhead, this restricts the "synchronization" overhead to those cases where there is an actual check to be done (i.e. "is the class loaded/initialized yet?").
One drawback of using the class loading mechanism is that it can be hard to debug when it breaks. If, for some reason, the Singleton constructor throws an exception, then the first caller to getInstance() will get that exception (wrapped in another one).
The second caller however will never see the root cause of the problem (he will simply get a NoClassDefFoundError). So if the first caller somehow ignores the problem, then you'll never be able to find out what exactly went wrong.
If you use simply synchronization, then the second called will just try to instantiate the Singleton again and will probably run into the same problem (or even succeed!).
A class is initialized when it's accessed at runtime. So init order is pretty much the execution order.
"Access" here refers to limited actions specified in the spec. The next section talks about initialization.
What's going on in your first example is equivalently
public static Singleton getSingleton()
{
synchronized( SingletonHolder.class )
{
if( ! inited (SingletonHolder.class) )
init( SingletonHolder.class );
}
return SingletonHolder.INSTANCE;
}
( Once initialized, the sync block becomes useless; JVM will optimize it off. )
Semantically, this is not different from the 2nd impl. This doesn't really outshine "double checked locking", because it is double checked locking.
Since it piggybacks on class init semantics, it only works for static instances. In general, lazy evaluation is not limited to static instances; imagine there's an instance per session.
First off, does Java actually have this problem? I know order within a class is fully specified but does it somehow guarantee consistent order between classes (such as with a class loader)?
It does, but to a lesser degree than in C++:
If there is no dependency cycle, the static initialization occurs in the right order.
If there is a dependency cycle in the static initialization of a group of classes, then the order of initialization of the classes is indeterminate.
However, Java guarantees that default initialization of static fields (to null / zero / false) happens before any code gets to see the values of the fields. So a class can (in theory) be written to do the right thing irrespective of the initialization order.
Secondly, if the order is consistent, why would the lazy construction option ever be advantageous?
Lazy initialization is useful in a number of situations:
When the initialization has side effects that you don't want to happen unless the object is actually going to be used.
When the initialization is expensive, and you don't want it to waste time doing it unnecessarily ... or you want more important things to happen sooner (e.g. displaying the UI).
When the initialization depends on some state that is not available at static initialization time. (Though you need to be careful with this, because the state might not be available when lazy initialization gets triggered either.)
You can also implement lazy initialization using a synchronized getInstance() method. It is easier to understand, though it makes the getInstance() fractionally slower.
The code in the first version is the correct and best way to safely lazily construct a singleton.
The Java Memory Model guarantees that INSTANCE will:
Only be initialized when first actually used (ie lazy), because classes are loaded only when first used
Be constructed exactly once so it's completely thread-safe, because all static initialization is guaranteed to be completed before the class is available for use
Version 1 is an excellent pattern to follow.
EDITED
Version 2 is thread safe, but a little bit expensive and more importantly, severely limits concurrency/throughput
I'm not into your code snippet, but I have an answer for your question. Yes, Java has an initialization order fiasco. I came across it with mutually dependent enums. An example would look like:
enum A {
A1(B.B1);
private final B b;
A(B b) { this.b = b; }
B getB() { return b; }
}
enum B {
B1(A.A1);
private final A a;
B(A a) { this.a = a; }
A getA() { return a; }
}
The key is that B.B1 must exist when creating instance A.A1. And to create A.A1 B.B1 must exist.
My real-life use case was bit more complicated - the relationship between the enums was in fact parent-child so one enum was returning reference to its parent, but the second array of its children. The children were private static fields of the enum. The interesting thing is that while developing on Windows everything was working fine, but in production—which is Solaris—the members of the child array were null. The array had the proper size but its elements were null because they were not available when the array was instantiated.
So I ended up with the synchronized initialization on the first call. :-)
The only correct singletone in Java can be declared not by class, but by enum:
public enum Singleton{
INST;
... all other stuff from the class, including the private constructor
}
The use is as:
Singleton reference1ToSingleton=Singleton.INST;
All other ways do not exclude repeated instantiation through reflection or if the source of class is directly present in the app source. Enum excludes everything. ( The final clone method in Enum ensures that enum constants can never be cloned )

Singleton pattern implementation from Wikipedia

I am referring to the solution for the Singleton Pattern by Bill Pugh on Wikipedia:
public class Singleton
{
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder
{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}
Here they have mentioned:
The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
However, isn't there a possibility that 2 threads would call getInstance() at the same time, which would lead to two instances of singleton being created? Isn't it safe to use synchronized here? If yes, where should it be used in the code?
See the "How it works", in the article "Initialization on demand holder idiom" linked from the same section.
In a nutshell, here's what happens when you call getInstance() the first time:
The JVM sees a reference to SingletonHolder it has never seen referenced before.
Execution is paused while it initializes SingletonHolder. This includes running any static initialization, which includes the singleton instance.
Execution resumes. Any other threads calling getInstance() at the same time will see that SingletonHolder is already initialized. The Java spec guarantees that class initialization is thread-safe.
The JLS guarantees the JVM will not initialize instance until someone calls getInstance(); and that will be thread safe because it would happen during the class initialization of SingletonHolder.
However, since Java 5, the preferred approach involves Enum:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
Reference: Implementing the singleton pattern in Java
Here is the explanation from Wikipedia on this phenomenon (emphasis mine):
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. The
initialization of the LazyHolder class
results in static variable something
being initialized by executing the
(private) constructor for the outer
class Something. Since the class
initialization phase is guaranteed by
the JLS to be serial, i.e.,
non-concurrent, no further
synchronization is required in the
static getInstance method during
loading and initialization. And since
the initialization phase writes the
static variable something in a serial
operation, all subsequent concurrent
invocations of the getInstance will
return the same correctly initialized
something without incurring any
additional synchronization overhead.
So in your example, Singleton is "LazyHolder" and SingletonHolder is "Something". Calling getInstance() twice will not cause a race condition due to the JLS guarantees.
I think the idea is that Java guarantees that a class can only be initialized once, so implicitly only the first thread to access would cause this to happen
The Singleton is created when Singleton.getInstance() is called at this time the INSTANCE will be instantiated.
Synchronization depends on a conrete implementation, since there are no values to modify (in this example) no synchronization is required.
There are two differences here that need to be noted. The first is the Singleton design pattern and the other is a singleton instance.
The Singleton design pattern is problematic due to the fact that the design pattern represents a singleton instance as is implemented using static state (which is a bad thing for a variety of reasons - especially with unit testing). The second is an instance for which there is only one instance, no matter what (like the JVM singleton implemented as an enum).
The enum version is definitely superior, when compared to the Singleton pattern.
If you don't want to implement all instances as enum instances, then you should think about using Dependency Injection (frameworks such as Google Guice) to manage the singleton instances for the application.
This idiom is known as the Initialization on Demand Holder (IODH) idiom and is discussed in Item 48 of Effective Java as reminded by Bob Lee in his great post about Lazy Loading Singletons:
Item 48: Synchronize access to shared mutable data
(...)
The initialize-on-demand holder
class idiom is appropriate for use
when a static field is expensive to
initialize and may not be needed, but
will be used intensively if it is
needed. This idiom is shown below:
// The initialize-on-demand holder class idiom
private static class FooHolder {
static final Foo foo = new Foo();
}
public static Foo getFoo() { return FooHolder.foo; }
The idiom takes advantage of the
guarantee that a class will not be
initialized until it is used [JLS,
12.4.1]. When the getFoo method is
invoked for the first time, it reads
the field FooHolder.foo, causing the
FooHolder class to get initialized.
The beauty of this idiom is that the
getFoo method is not synchronized
and performs only a field access, so
lazy initialization adds practically
nothing to the cost of access. The
only shortcoming of the idiom is that
it does not work for instance fields,
only for static fields.
However, in the Second Edition of Effective Java, Joshua explains how enums can be (ab)used for writing a serializable Singleton (this should be the preferred way with Java 5):
As of release 1.5, there is a third approach to implementing singletons. Simply
make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it
is more concise, provides the 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.

Categories

Resources