singleton with immutable class in java - java

class MyClass
{
private static volatile Resource resource;
public static Resource getInstance()
{
if(resource == null)
resource = new Resource();
return resource;
}
}
Here if the Resource is a immutable class, is it safe to write the above code? As in java concurrency in practice it's mentioned that "initialization safety allow properly constructed immutable objects to be safely shared across thread.So the above code is safe to be written." (in page no 349 16.3). But with this it may possible if two threads checks for the null and they can proceed for object creation which is against the invariant of the class (singleton). please explain. A continuation of the question in
link

No, this is not threadsafe code. In this case, Resource might be threadsafe, but your getInstance method is not.
Imagine this sequence of events
Thread1 calls getInstance and checks "if resource == null" and then stops (because the OS said it was time for it to be done) before initializing the resources.
Thread2 calls getInstance and checks "if resource == null" and then initializes the instance
Now Thread1 starts again and it also initializes the instance.
It has now been initialized twice and is not a singleton.
You have a couple of options to make it thread safe.
Make the getInstance method synchronized
Initialize the instance on declaration (or in a static initializer), and getInstance can just return it.
You also don't need to make the variable volatile. In case #1, synchronizing the method flushes the variable anyway so all variables will see an updated copy. In case #2, the object is guaranteed to be visible to all objects after construction.

Related

Singleton without volatile member

Let's say I have next class:
public class Singleton{
private static Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
For example we have two threads A and B which try to execute getInstance() method simultaneously. Am I understand the process correctly:
Thread A enter into getInstance() method and acquire the lock;
Thread B also enter into getInstance() method and blocked;
Thread A create new Singleton() object and release the lock, now last value of _instance variable should be visible to thread B? Or thread B still could have own copy of _instance variable which is not synchronized with the main memory(_instance=null)?
Thread B is blocked on the synchronize, when it proceeds it will see the changed field _instance != null and therefore does not construct one but return the existing.
All other threads which come later see the instance being set and will not even lock.
Problem: your code is incomplete, you need volatile in order to make sure threads which do not go through the synchronized (most of them, hopefully) still only see a completely published singleton object.
The Java Memory Model does only guarantee that the final fields are initialized. For all others you need a safe publish, which is possible with:
Exchange the reference through a properly locked field (JLS 17.4.5)
Use static initializer to do the initializing stores (JLS 12.4)
Exchange the reference via a volatile field (JLS 17.4.5), or as the consequence of this rule, via the AtomicX classes
Initialize the value into a final field (JLS 17.5).
The easiest method to avoid the volatile (or an atomic reference which is also safe to publish objects to other threads) is to use normal Object initialisation, this is a valid and robust singleton (but not lazy) provided by the JVM:
class Singleton
{
private static final Singleton HIGHLANDER = new Singleton();
private Singleton() { } // not accessible
public static getSingleton() { return HIGHLANDER; }
}
JDK internally uses this similar construct with "Holder" objects to implement the same simple and robust pattern but in a lazy fashion:
class Singleton
{
private Singleton() { } // not accessible
private static Class LazyHolder {
private static final Singleton LAZY_HIGHLANDER = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.LAZY_HIGHLANDER;
}
}
Both methods do not require volatile variable access (which you need in DCL case) or synchronisation (it is implicitly done by the JVM which does the initialisation protected by a class lock).
What you show here is called double-checked locking.
The static variable belongs to the class, not the thread. Both threads will see the proper value, but it is possible that the compiler may optimize the reads such that the static variable is not checked both times. For this reason, you should declare the variable with the volatile keyword.
Please note that in versions of Java prior to version 5 this might not work correctly even with a volatile variable. It used to be possible for the assignment to assign a partially-constructed object to the variable. Now the constructor must return before the assignment can proceed. This will work correctly in any modern version Java.
Two problems that could exist as far as I know.
Thread B might or might not see the latest value.
Thread B might see a partially constructed object, incase there are a lot of things that the constructor does, and JVM decides to change the ordering of the code.
Making it volatile solves both problems, since it enforces the happens before relationship and stops JVM from re ordering the code execution, and updates the values in the other threads.

How make a synchronized Singleton design pattern in Java?

I have gone through a singleton design pattern in Java which is below mentioned. I am having trouble to understand how does the Synchronized keyword in the public static getter or accessor method prevent more than one object creation ?
If at all it is being called twice from two different classes Synchronized should make their calls Synchronized i.e. one after the other . How does it govern only one object creation?
Please explain in details and also check the comments if my assumptions about the modifiers are correct or not
class MySingleton
{
private static MySingleton singletonObj; //as it is private it cannot be referenced outside of this class
//and as it is static all the instances of this class share the same copy of this refrence variable
private MySingleton()
{
System.out.println("Welcome to a singleton design pattern");
System.out.println("Objects cannot be instantiated outside of this class");
}
public static synchronized MySingleton getASingletonObject()
{
if(singletonObj==null)
{
singletonObj=new MySingleton();
}
return singletonObj;
}
}
Help is much appreciated :)
Thanks
Your question is about the way it works: You have one instance not because of the synchronized, but because it is stored in a static variable, and is instancied only one time (with a lazy creation - checked by the if).
The synchronized ensure you that only one Thread will instanciate the object, and avoid a bug where many Threads could create duplicates.
Here is the other way to implement it, and i find it more simple, and as efficient:
public class Singleton
private static final Singleton instance=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
Note: the only condition for using this kind of implementation is that your constructor (the new) should not throw any exception, and should only contain simple code like variable initialisation.
The purpose of the Singleton class is that there is at most one instance of it and, hence, all threads access that same object.
Supposing there are 'n' threads trying to access the getASingletonObject method.
Case I:If we don't synchronize the getASingletonObject method the following could happen:
1) Thread1 enters getASingletonObject()
2) Thread2 enters getASingletonObject()
3) Thread1 evaluates singletonObj == null to true
4) Thread2 evaluates singletonObj == null to true
5) Thread1 assigns singletonObj and returns
6) Thread2 *re*assigns singletonObj = new Singleton() and returns.
Now the threads both have a difference instance of the Singleton class which is what should have been prevented by this pattern.
Synchronizing prevents that both Threads can access the same block of code at the same time. So synchronization is needed in a multithreaded environment when you instantiate singleton classes.
Now assuming that multple threads will attempt to access the Singletons methods at the same time synchronization might be neccessary on those methods as well. Especially if they change data instead of only reading it this is true.
You´re not implementing correctly Singleton patter look my implementation.
class MySingleton
{
private MySingleton instance; //You dont need that you instance be static, inside your class you have all the access of the Instance once you call getInstance()
public static MySingleton getInstance(){
return instance;
}
private MySingleton()
{
System.out.println("Welcome to a singleton design pattern");
System.out.println("Objects cannot be instantiated outside of this class");
}
public static synchronized MySingleton getASingletonObject()
{
if(instance==null)
{
instance=new MySingleton();
}
return instance;
}
}
//About the synchronized you have to understand that is like a lock, where every time a thread is getting inside he is closing the method so nobody else can be inside and then there´s no possible that when a thread is in the line instance=new MySingleton(); but has not being executed for the VM another thread would be in if(instance==null) asking the VM and returning true.
As soon as the first tread is out of the method the lock is open and then other threads can get in. And then they will see that the instance is already created.
The synchronized keyword protects the singleton member variable (singletonObj in this case) from multithreaded access. This ensures that even if multiple threads are trying to create an object, only one is still being used.
Check this article: http://www.javaworld.com/article/2073352/core-java/simply-singleton.html for more explanation.
Wikipedia says:
In software engineering, the singleton pattern is a design pattern
that restricts the instantiation of a class to one object.
So you create singletonObj only one-time because when you call getASingletonObject() you check is singletonObj == null and if it's null, so you create a new object, if it's not null you get 'singletonObj' created before.
public static synchronized gives you confidence that this object have been created once, because static says that singletonObj have been created once for class, but not for concrete instance of object. And synchronized provides a concurrent access to getASingletonObject() and it's give you confidence that object singletonObj couldn't be created twice when different threads call your method simultaneously.

Instance methods and thread-safety of instance variables

I would like to known if each instance of a class has its own copy of the methods in that class?
Lets say, I have following class MyClass:
public MyClass {
private String s1;
private String s2;
private String method1(String s1){
...
}
private String method2(String s2){
...
}
}
So if two differents users make an instance of MyClass like:
MyClass instanceOfUser1 = new MyClass();
MyClass instanceOfUser2 = new MyClass();
Does know each user have in his thread a copy of the methods of MyClass? If yes, the instance variables are then thread-safe, as long as only the instance methods manipulate them, right?
I am asking this question because I often read that instance variables are not thread-safe. And I can not see why it should be like that, when each user gets an instance by calling the new operator?
Each object gets its own copy of the class's instance variables - it's static variables that are shared between all instances of a class. The reason that instance variables are not necessarily thread-safe is that they might be simultaneously modified by multiple threads calling unsynchronized instance methods.
class Example {
private int instanceVariable = 0;
public void increment() {
instanceVariable++;
}
}
Now if two different threads call increment at the same then you've got a data race - instanceVariable might increment by 1 or 2 at the end of the two methods returning. You could eliminate this data race by adding the synchronized keyword to increment, or using an AtomicInteger instead of an int, etc, but the point is that just because each object gets its own copy of the class's instance variables does not necessarily mean that the variables are accessed in a thread-safe manner - this depends on the class's methods. (The exception is final immutable variables, which can't be accessed in a thread-unsafe manner, short of something goofy like a serialization hack.)
Issues with multi-threading arise primarily with static variables and instances of a class being accessed at the same time.
You shouldn't worry about methods in the class but more about the fields (meaning scoped at the class level). If multiple references to an instance of a class exist, different execution paths may attempt to access the instance at the same time, causing unintended consequences such as race conditions.
A class is basically a blueprint for making an instance of an object. When the object is instantiated it receives a spot in memory that is accessed by a reference. If more than one thread has a handle to this reference it can cause occurrences where the instance is accessed simultaneously, this will cause fields to be manipulated by both threads.
'Instance Variables are not thread safe' - this statement depends on the context.
It is true, if for example you are talking about Servlets. It is because, Servlets create only one instance and multiple threads access it. So in that case Instance Variables are not thread safe.
In the above simplified case, if you are creating new instance for each thread, then your instance variables are thread safe.
Hope this answers your question
A method is nothing but a set of instructions. Whichever thread calls the method, get a copy of those instructions. After that the execution begins. The method may use local variables which are method and thread-scoped, or it may use shared resources, like static resources, shared objects or other resources, which are visible across threads.
Each instance has its own set of instance variables. How would you detect whether every instance had a distinct "copy" of the methods? Wouldn't the difference be visible only by examining the state of the instance variables?
In fact, no, there is only one copy of the method, meaning the set of instructions executed when the method is invoked. But, when executing, an instance method can refer to the instance on which it's being invoked with the reserved identifier this. The this identifier refers to the current instance. If you don't qualify an instance variable (or method) with something else, this is implied.
For example,
final class Example {
private boolean flag;
public void setFlag(boolean value) {
this.flag = value;
}
public void setAnotherFlag(Example friend) {
friend.flag = this.flag;
}
}
There's only one copy of the bytes that make up the VM instructions for the setFlag() and setAnotherFlag() methods. But when they are invoked, this is set to the instance upon which the invocation occurred. Because this is implied for an unqualified variable, you could delete all the references to this in the example, and it would still function exactly the same.
However, if a variable is qualified, like friend.flag above, the variables of another instance can be referenced. This is how you can get into trouble in a multi-threaded program. But, as long as an object doesn't "escape" from one thread to be visible to others, there's nothing to worry about.
There are many situations in which an instance may be accessible from multiple classes. For example, if your instance is a static variable in another class, then all threads would share that instance, and you can get into big trouble that way. That's just the first way that pops into my mind...

Singleton instantiated with double-checked blocking method

I have a question about this instantiation method:
From this web site it says:
class Singleton
{
private static Singleton instance;
private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class)
{
if (instance == null)
{
System.out.println("getInstance(): First time getInstance was invoked!");
instance = new Singleton();
}
}
}
return instance;
}
public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}
However from the book "Head First Design Pattern" by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson, they instantiate the Singleton using the same method, with the only difference that they declare the private static member as volatile and they rim the point quite a bit about declaring it volatile. Should not be enough declaring the "critical zone" synchronized in order to establish the proper "happnens-before relationship" between threads?
As per the defininition, using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
The problem is that an out-of-order write may allow the instance reference to be returned before the Singleton constructor is executed.
Thread A notices that the value is not initialized, so it obtains the lock and begins to initialize the value.
Due to the semantics of programming languages, the code generated by the compiler is allowed to update the shared variable to point to a partially constructed object before A has finished performing the initialization. For example, in Java if a call to a constructor has been inlined then the shared variable may immediately be updated once the storage has been allocated but before the inlined constructor initializes the object.
Thread B notices that the shared variable has been initialized (or so it appears), and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B (either because A has not finished initializing it or because some of the initialized values in the object have not yet percolated to the memory B uses (cache coherence)), the program will likely crash.
Read this wiki for a clear explanation of things: http://en.wikipedia.org/wiki/Double_checked_locking_pattern#Usage_in_Java

What is the difference between synchronized(this) and synchronized(ClassName.class)?

I read somewhere that synchronized(this) should be avoided for various reasons. Yet some respectable code that I encountered uses the following in the constructor:
public SomeClass(Context context) {
if (double_checked_lock == null) {
synchronized (SomeClass.class) {
if (double_checked_lock == null) {
// some code here
}
}
}
}
Is there really a difference between synchronized(this) and synchronized(SomeClass.class)?
synchronized(this) is synchronized on the current object, so only one thread can access each instance, but different threads can access different instances. E.g. you can have one instance per thread.
This is typically useful to prevent multiple threads from updating an object at the same time, which could create inconsistent state.
synchronized(SomeClass.class) is synchronized on the class of the current object ( or another class if one wished) so only one thread at a time can access any instances of that class.
This might be used to protect data that is shared across all instances of a class (an instance cache, or a counter of the total number of instances, perhaps) from getting into an inconsistent state .
this is different for each instance.
ClassName.class is not.
Therefore, synchronized(this) will allow multiple instance to run simultaneously.
The synchronized keyword, when applied to a class locks on the class, and when it's applied to this locks on the current object instance. From the Java Language Specification, section 8.4.3.6, 'synchronized Methods':
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.
Each java Object can have a lock. This lock can be held by at most one thread at a time, any other thread has to wait to get the lock of the same object.
synchronized(this) acquires the lock of the instance this for the current thread. The method can run parallel on different instances (different values for this and therefore different locks)
synchronized(SomeClass.class) acquires the lock of the global class object of SomeClass. Only one instance of the method can run as all object instances lock on the same global object (same lock).
These are 2 different object to lock on:
'this' refer to current instance context, so creating multiple instances will have no effect if, for example, each thread using a different instance and lock on it. 'this' can be referred only on non-static context.
the 'class' is a static member of the Java Class and there is exactly one instance of it. You can lock on it in both static and non-static context.
synchronized(this) synchronizes on the instance of the object.
synchronized(SomeClass.class)uses the instance of the Class object that represents SomeClass, which is global for all instances in the same classloader.
Thus, these are different constructs with different semantics.
Using synchronized alone, or as a method modifier, also synchronizes on the instance's semaphore, which is normally used to prevent contention between multiple threads accessing that instance as a shared resource (i.e. a List).
The thread you refer states that it's a better practice to use a private instance, as synchronizing directly on your object instance may be dangerous. For that you'd use:
class MySharedResourceClass {
private SomeClass lock = new SomeClass();
public doSomething() {
synchronized (lock) {
// Do something here
}
}
}

Categories

Resources