This question already has answers here:
Java: Lazy Initializing Singleton
(5 answers)
Closed 9 years ago.
I was going through design pattern and came across with Singleton Pattern
class SingletonPattern implements Runnable {
private static SingletonPattern single=null;
private SingletonPattern() { }
public synchronized static SingletonPattern getInstance() {
if(null==single) {
single=new SingletonPattern();
}
return single;
}
}
Now I understand that synchronized will help that two thread cannot access the getInstance method but correct me if I am wrong two different object will have two locks each having one.Another thread can be started from anther object and get then access the getInstance() method thus we can have two objects.??
No. The synchronized method will prevent 2 threads from simultaneously calling the method. You can read up on synchronized here. In case of a static method, the synchronized acts on the class rather than object.
However, this way of making Singletons is inefficient. And Double Checked Locking is broken. The best way to do singletons in java is by using a Enum
The variable single is static. That is to say, all instance of class SingletonPattern share the same variable single. The first time the function getInstance() execute, the variable single is null, so
single = new SingletonPattern();
executes, which makes variable single not null any more.
Then all the successive call of function getInstance() would not enter the if clause, thus only return the same variable single, which is a reference to the same instance of the class SingletonPattern.
Also the synchronized keyword makes sure the function getINstance() would not be called in two threads at the same time.
No. Since getInstance and single are static both threads will use the very same method and object so there won't be two objects. synchronized will ensure that they won't access simultaneously inside getInstance
synchronized static method will acquire Class lock and there is a single class lock available for all objects of this class. Hence different objects will be prevented from acquiring this lock at the same time.
But this mechanism works as long as different classloaders are not involved.
Although best way to implement singletons in java is to use enums
Related
This question already has answers here:
Clarification on the meaning of the parameter block synchronization
(3 answers)
What does 'synchronized' mean?
(17 answers)
How does synchronized work in Java
(4 answers)
Closed 2 years ago.
There is a lot of material on stack-overflow about synchronization, but I still haven't acquired quality content about deciding which object to use as an intrinsic lock. Can some one actually make a good answer as a rule of thumb?
So should I choose 'monitor' as an instance variable or local variable or instance owning the method? All three of them do the job well. Also primitive value wrapper classes use 'pools' so no problem there as well, as threads 'attack' the same lock.
So why is it better to do this (this):
class A {
void methodA(){
synchronized (this){
//some code
}
}
}
over this(instance variable):
class A {
String monitor = "monitor";
void methodA(){
synchronized (monitor){
//some code
}
}
}
or over this(local variable):
class A {
void methodA(){
String monitor = "monitor";
synchronized (monitor){
//some code
}
}
}
They all work fine/same. So why did I read that I should avoid local variables when they implicitly use pools to store objects? What matter does the scope of variables make in this case?
Thanks!
You should avoid using the monitor of objects stored in local variables because typically only the current thread has access to objects stored in local variables. But since in this particular case, the local variable actually holds a globally shared object from the constant pool, you don't suffer from that particular problem.
The problem with using monitors of constant pool objects like here:
String monitor = "monitor";
void methodA() {
synchronized (monitor){
//some code
}
}
... is that there is only one pooled constant object.
Two different threads operating on two different instances of class A cannot enter the synchronized block in methodA at the same time, even if you've ensured it should be safe (for example, you don't touch static shared state).
What's even worse: there might be some other class B somewhere else, which also happens to synchronize on the constant "monitor" string. Now a thread using class B will block other, unrelated, threads from using class A.
On top of that, it's incredibly easy to create a deadlock because you are unknowingly sharing locks between threads.
I am aware of locking concepts with synchronization of static and non static methods to lock classes and instances respectively. What I am not able to understand is, how is class level lock achieved? I mean, class is a template only, with no physical significance. So, when we say that class level locking is achieved with synchronizing static methods what happens then? Do all the objects of that class get locked or some other process?
With what I could find out with my search is that there are class objects (Class.class) and lock is acquired on this class object. But then how are all instances of that class also locked?
Do all the objects of that class get locked or some other process?
First, let's talk about what what it means to "lock" an object.
Foobar foobar = new Foobar();
synchronized (foobar) {
...
}
You might say that the foobar object is "locked" when a thread is in the synchronized block. But what does that do for the program? A lot of newbies make the mistake of thinking that it will prevent other threads from accessing the object. But, that is not true. What synchronized does--the only thing synchronized does--is to guarantee that no more than one thread can be synchronized on the same object at the same time.
The programmer's intent in the example above might be to prevent other threads from seeing foobar in an inconsistent state. In that case, every method and every fragment of code that accesses foobar must be synchronized on foobar. Imagine foobar as big room with many doors. Each method that uses foobar is like a different door. If you want to keep people out of the room, it doesn't help to lock just one door. You have to lock all of them.
So now, to your question:
when we say that class level locking is achieved with synchronizing static methods what happens then?
Simple. This:
class Foobar {
static synchonized void do_something() {
...
}
}
Does exactly the same as this:
class Foobar {
static void do_something() {
synchronized(Foobar.class) {
...
}
}
}
You always synchronize on an Object. Well, a class is an Object. When a static method is synchronized, that just means that the method body is synchronized on the class object.
Since a class is a singleton object, that means that no two threads can get into the same static synchronized method at the same time. In my earlier example, the variable foobar could refer to different objects at different times, but in the static example, Foobar.class is guaranteed always to refer to the same singleton.
Edit: As, #Danny pointed out, there is no connection between a block that is synchronized on the Foobar class, (my second example) and a block that is synchronized on an instance of the Foobar class (my first example). The instance and the class object are two different objects, so nothing prevents one thread from synchronizing on the instance while another thread is synchronized on the class. Likewise, nothing prevents two different threads from synchronizing on two different instances. Another mistake that newbies often make is to think that only one thread at a time can enter this synchronized block:
Integer n = ...;
synchronized (n) {
n = n+1;
...
}
But it's not true. It's not the variable, n, that is locked, it's a particular instance of the Integer class. Each thread that enters the block creates a new Integer instance and assigns it to n. So when the next thread comes along, n no longer refers to the same instance that the first thread has synchronized.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java Synchronized Block for .class
I was reading through an article on synchronization. I am confused on below points and need more clarification
For synchronization block. How
synchronized (this) {
// code
}
differs from
synchronized (MyClass.class) {
// code
}
Synchronizing instance method means threads will have to get exclusive lock on the instance, while synchronizing static method means thread will have to acquire a lock on whole class(correct me if I am wrong). So if a class has three methods and one of them is static synchronized then if a thread acquires lock on that method then that means it will acquire lock on the whole class. So does that mean the other two will also get locked and no other method will be able to access those two methods as the whole class is having lock?
MyClass.class and this are different things, they are different references to different objects.
this - is a reference to this particular instance of the class, and
MyClass.class - is a reference to the MyClass description object.
These synchronization blocks differ in that the first will synchronize all threads that deal concretely with this instance of MyClass, and the second one will synchronize all threads independently of which object on which method was called.
The first example (acquiring lock on this) is meant to be used in instance methods, the second one (acquiring lock on class object) -- in static methods.
If one thread acquires lock on MyClass.class, other threads will have to wait to enter the synchronized block of a static method that this block is located in. Meanwhile, all of the threads will be able to acquire lock for a particular instance of this class and execute instance methods.
I'm trying to learn about singleton classes and how they can be used in an application to keep it thread safe. Let's suppose you have an singleton class called IndexUpdater whose reference is obtained as follows:
public static synchronized IndexUpdater getIndexUpdater() {
if (ref == null)
// it's ok, we can call this constructor
ref = new IndexUpdater();
return ref;
}
private static IndexUpdater ref;
Let's suppose there are other methods in the class that do the actual work (update indicies, etc.). What I'm trying to understand is how accessing and using the singleton would work with two threads. Let's suppose in time 1, thread 1 gets a reference to the class, through a call like this IndexUpdater iu = IndexUpdater.getIndexUpdater(); Then,
in time 2, using reference iu, a method within the class is called iu.updateIndex by thread 1. What would happen in time 2, a second thread tries to get a reference to the class. Could it do this and also access methods within the singleton or would it be prevented as long as the first thread has an active reference to the class. I'm assuming the latter (or else how would this work?) but I'd like to make sure before I implement.
Thank you,
Elliott
Since getIndexUpdater() is a synchronized method, it only prevents threads from accessing this method (or any method protected by the same synchronizer) simultaneously. So it could be a problem if other threads are accessing the object's methods at the same time. Just keep in mind that if a thread is running a synchronized method, all other threads trying to run any synchronized methods on the same object are blocked.
More info on:
http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
Your assumption is wrong. Synchronizing getIndexUpdater() only prevents more than one instance being created by different threads calling getIndexUpdater() at (almost) the same time.
Without synchronization the following could happen: Thread one calls getIndexUpdater(). ref is null. Thread 2 calls getIndexUpdater(). ref is still null. Outcome: ref is instantiated twice.
You are conflating the instantiation of a singleton object with its use. Synchronizing the creation of a singleton object does not guarantee that the singleton class itself is thread-safe. Here is a simple example:
public class UnsafeSingleton {
private static UnsafeSingleton singletonRef;
private Queue<Object> objects = new LinkedList<Object>();
public static synchronized UnsafeSingleton getInstance() {
if (singletonRef == null) {
singletonRef = new UnsafeSingleton();
}
return singletonRef;
}
public void put(Object o) {
objects.add(o);
}
public Object get() {
return objects.remove(o);
}
}
Two threads calling getInstance are guaranteed to get the same instance of UnsafeSingleton because synchronizing this method guarantees that singletonRef will only be set once. However, the instance that is returned is not thread safe, because (in this example) LinkedList is not a thread-safe queue. Two threads modifying this queue may result in unexpected behavior. Additional steps have to be taken to ensure that the singleton itself is thread-safe, not just its instantiation. (In this example, the queue implementation could be replaced with a LinkedBlockingQueue, for example, or the get and put methods could be marked synchronized.)
Then, in time 2, using reference iu, a method within the class is called iu.updateIndex by thread 1. What would happen in time 2, a second thread tries to get a reference to the class. Could it do this and also access methods within the singleton ...?
The answer is yes. Your assumption on how references are obtained is wrong. The second thread can obtain a reference to the Singleton. The Singleton pattern is most commonly used as a sort of pseudo-global state. As we all know, global state is generally very difficult to deal with when multiple entities are using it. In order to make your singleton thread safe you will need to use appropriate safety mechanisms such as using atomic wrapper classes like AtomicInteger or AtomicReference (etc...) or using synchronize (or Lock) to protect critical areas of code from being accessed simultaneously.
The safest is to use the enum-singleton.
public enum Singleton {
INSTANCE;
public String method1() {
...
}
public int method2() {
...
}
}
Thread-safe, serializable, lazy-loaded, etc. Only advantages !
When a second thread tries to invoke getIndexUpdater() method, it will try to obtain a so called lock, created for you when you used synchronized keyword. But since some other thread is already inside the method, it obtained the lock earlier and others (like the second thread) must wait for it.
When the first thread will finish its work, it will release the lock and the second thread will immediately take it and enter the method. To sum up, using synchronized always allows only one thread to enter guarded block - very restrictive access.
The static synchronized guarantees that only one thread can be in this method at once and any other thread attempting to access this method (or any other static synchronized method in this class) will have to wait for it to complete.
IMHO the simplest way to implement a singleton is to have a enum with one value
enum Singleton {
INSTANCE
}
This is thread safe and only creates the INSTANCE when the class is accessed.
As soon as your synchronized getter method will return the IndexUpdater instance (whether it was just created or already existed doesn't matter), it is free to be called from another thread. You should make sure your IndexUpdater is thread safe so it can be called from multiple threads at a time, or you should create an instance per thread so they won't be shared.
What does this java code mean? Will it gain lock on all objects of MyClass?
synchronized(MyClass.class) {
//is all objects of MyClass are thread-safe now ??
}
And how the above code differs from this one:
synchronized(this) {
//is all objects of MyClass are thread-safe now ??
}
The snippet synchronized(X.class) uses the class instance as a monitor. As there is only one class instance (the object representing the class metadata at runtime) one thread can be in this block.
With synchronized(this) the block is guarded by the instance. For every instance only one thread may enter the block.
synchronized(X.class) is used to make sure that there is exactly one Thread in the block. synchronized(this) ensures that there is exactly one thread per instance. If this makes the actual code in the block thread-safe depends on the implementation. If mutate only state of the instance synchronized(this) is enough.
To add to the other answers:
static void myMethod() {
synchronized(MyClass.class) {
//code
}
}
is equivalent to
static synchronized void myMethod() {
//code
}
and
void myMethod() {
synchronized(this) {
//code
}
}
is equivalent to
synchronized void myMethod() {
//code
}
No, the first will get a lock on the class definition of MyClass, not all instances of it. However, if used in an instance, this will effectively block all other instances, since they share a single class definition.
The second will get a lock on the current instance only.
As to whether this makes your objects thread safe, that is a far more complex question - we'd need to see your code!
Yes it will (on any synchronized block/function).
I was wondering about this question for couple days for myself (actually in kotlin). I finally found good explanation and want to share it:
Class level lock prevents multiple threads to enter in synchronized block in any of all available instances of the class on runtime. This means if in runtime there are 100 instances of DemoClass, then only one thread will be able to execute demoMethod() in any one of instance at a time, and all other instances will be locked for other threads.
Class level locking should always be done to make static data thread safe. As we know that static keyword associate data of methods to class level, so use locking at static fields or methods to make it on class level.
Plus to notice why .class. It is just because .class is equivalent to any static variable of class similar to:
private final static Object lock = new Object();
where lock variable name is class and type is Class<T>
Read more:
https://howtodoinjava.com/java/multi-threading/object-vs-class-level-locking/