Java Multithreading : Creating a Singleton Object [duplicate] - java

This question already has answers here:
Why is volatile used in double checked locking
(8 answers)
Closed 8 years ago.
What's the difference between a static and volatile reference from threading point of view?
For example I want to have a singleton object and my code is like this:
class Singleton {
Helper helper; /*Shall I make this variable static or volatile*/
Helper getHelper() {
if(helper==null) {
synchronized(this) {
if(helper==null) {
helper=new Helper();
}
}
}
return helper;
}
}
Suppose there are two threads accessing the getHelper() method. To avoid multiple creation of Helper object and dirty read shall I make the reference static or volatile?
Can anyone please explain taking thread cache into picture?

For this sort of lazy initialization it needs to be volatile.
For it to be a singleton it needs to be static.
So you need both :)
There is a much neater pattern you can use for lazy initialization of a static singleton though which uses the class loader to do all the work for you:
class Singleton {
private static class SingletonHolder {
private static final Singleton instance;
}
Singleton getInstance() {
return SingletonHolder.instance;
}
}
The inner class is only loaded the first time you use it, which means it is lazily loaded from the point of view of the outer class. The class loader handles all of your synchronization for you though.

From Head First Design Patterns if application is multitasking, you should use a private volatile static modificators.
Volatile modifier ensures, that field is handled properly in multithread environment. Without it, there still might be a situation, where more than one object will by created.
So your code should be like
class Singleton {
private volatile static Helper helper;
public static Helper getInstance(){
if(helper==null) {
synchronized(this) {
if(helper==null){
helper=new Helper();
}
}
}
return helper;
}
}

If Helper is a heavy class and you only want to have a single one (inside your Singleton) you should make it static. The instantiation inside the synchronized block will stop it causing issues. However, any non-thread-safe methods inside your Helper class should also be appropriately synchronized.

Related

How to make sure that there is just one instance of class in JVM?

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a single point, but I don't know if it is possible.
I can only think of a way to count instances of a class and destroy all instance after first is created.
Is this a right approach? If not, is there any other way?
Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
Note that the method of using “lazy evaluation” in the getInstance() method (which
is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy
loading.” Your singleton class will probably not get loaded unless its getInstance()
is called, so there is no point in trying to defer the singleton construction until it’s needed
by having getInstance() test the singleton variable for null and creating the singleton
there.
Using this class is equally simple: simply get and retain the reference, and invoke methods on it:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
Some commentators believe that a singleton should also provide a public final
clone() method that just throws an exception, to avoid subclasses that “cheat” and
clone() the singleton. However, it is clear that a class with only a private constructor
cannot be subclassed, so this paranoia does not appear to be necessary.
That's the well known Singleton pattern: you can implement this as follows:
public class SingletonClass {
//this field contains the single instance every initialized.
private static final instance = new SingletonClass();
//constructor *must* be private, otherwise other classes can make an instance as well
private SingletonClass () {
//initialize
}
//this is the method to obtain the single instance
public static SingletonClass getInstance () {
return instance;
}
}
You then call for the instance (like you would constructing a non-singleton) with:
SingletonClass.getInstance();
But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...
There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.
Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter.
The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).
You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.
Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.
Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.
See this StackOverflow question for more details:
Implementing Singleton with an Enum (in Java)
Discussion:
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
I can only think of a way to count instances of a class and destroy all instance after first is created. Is this a right approach ? If not, is there any other way ?
The correct technical approach is to declare all of the constructors for the class as private so that instances of the class can only be created by the class itself. Then you code the class only ever create one instance.
Other Answers show some of the ways to implement this, according to the "Singleton" design pattern. However, implementing a singleton like this has some drawbacks, including making it significantly harder to write unit tests.
I prefer lazy singleton class, which overrides readResolve method.
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.
Lazy singleton using /Initialization-on-demand_holder_idiom:
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Key notes:
final keyword prohibits extension of this class by sub-classing
private constructor prohibits direct object creation with new operator in caller classes
readResolve prohibits creation of multiple instances of class during object de-serialization
For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.
E.g: If I want only one object for this Connect class:
public final class Connect {
private Connect() {}
private volatile static Connect connect = null;
public static Connect getinstance() {
if(connect == null) {
synchronized (Connect.class) {
connect = new Connect();
}
}
return connect;
}
}
Here the constructor is private, so no one can use new keyword to make a new instance.
class A{
private A(){
}
public static A creator(A obj){
A ob=new A();
return ob;
}
void test(){
System.out.println("The method is called");
}
}
class Demo{
public static void main(String[] args){
A ob=null;
ob=A.creator(ob);
ob.test();
}
}

Singleton using Static Members and Methods? [duplicate]

This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 9 years ago.
We can replicate a Singleton behavior my making a Class with Static Methods and Member Elements. Other than serialization What's the harm of implementing a singleton using static Body only.
You can't use this pattern to implement a provider for some interface or to allow for subclassing or other alternate behavior. This means that testing becomes more difficult and you can't use dependency injection for anything your static class does.
A Singleton is a single instance of a class (i.e., one object). A block of static code is not an object. It's just code.
It seems there is a definite difference between this:
public class MyClass {
public static void doIt() {
System.out.println("doIt()");
}
}
And this:
public class MySingleton {
private static MySingleton _singleton = null;
private String cantTouchThis;
private MySingleton() {
cantTouchThis = "Hands off, static block!";
}
public static MySingleton newInstance() {
if (_singleton == null) {
_singleton = new MySingleton();
}
return _singleton;
}
}
In the first case, basically all you have is a block of code you can execute by calling MyClass.doIt(). In the second, by calling MySingleton.newInstance() you can get your hands on an honest-to-goodness object.
HTH
Akwardness or hoop-jumping to unit test such a "singleton" is one potential downside in addition to serialization.
Contrast this with unit testing a true (i.e. instantiable) singleton.
Ultimately, a singleton guarantees a single instance of a class, whereas a static class is not instantiable as #JStevenPerry points out (and I expect you already understand): the two are simply not the same although they can in many ways be employed similarly.

What is the point of making the singleton instance volatile while using double lock? [duplicate]

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
}

Threading : Lazy Initialization vs Static Lazy Initialization

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/

Thread Safe Efficient way to implement singleton pattern in Java? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Efficient way to implement singleton pattern in Java
I was reading this Best Singleton Implementation In Java, but its not thread safe.
As per wiki :
if(singleton==null) {
synchronized(Singleton.class) { //
this is needed if two threads are
waiting at the monitor at the // time
when singleton was getting
instantiated if(singleton==null)
singleton= new Singleton(); }
}
But Find Bugs utility gives two errors in this :
1. Double null check.
2. Incorrect lazy initialization of static field.
What is the best way,
Is it Correct :
synchronized (Singleton.class) {
if (singleton== null) {
singleton= new Singleton();
}
}
The most efficient/simplest way to make a lazy loading Singleton is just
enum Singleton {
INSTANCE
}
Note: there is no need for locking as class loading is thread safe. The class is final by default and the constructor cannot be called via reflection. The INSTANCE will not be created until the INSTANCE, or the class is used. If you are worried the class might be accidentally used you can wrap the singleton in an inner class.
final class Singleton {
private Singleton() { }
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
IMHO, you have to be pretty paranoid to consider this a better solution.
A lot has been written about this issue. Yes, the simple double-check-locking pattern is not safe. But you can make it safe by declaring the static instance as volatile. The new Java Memory Model specification adds some code-reordering restrictions for compilers when dealing with volatile, therefore the original risks are gone.
Anyway, I rarely really need this kind of lazyness when creating the instance, so I usually simply create it statically at class-loading time:
private static MyClass instance = new MyClass();
This is short and clear. As an alternative, if you really want to make it lazy, you can take advantage of the class loading characteristics and do this:
public class MyClass {
private static class MyClassInit {
public static final MyClass instance = new MyClass();
}
public static MyClass getInstance() {
return MyClassInit.instance;
}
...
}
The nested class will not be loaded until the first time you call getInstance().
The first code sample in the accepted answer for Efficient way to implement singleton pattern in Java is thread safe. The creation of the INSTANCE is performed by the class loader the first time the class is loaded; it's performed exactly once, and in a thread-safe way:
public final class Foo {
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
}
(copied from What is an efficient way to implement a singleton pattern in Java?)
The 2nd code sample in the question is correct and thread-safe, but it causes synchronization on each call to getInstance(), which affects performance.

Categories