Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between synchronized(this) vs synchronized(someClass.class)  RSS feed

 
Yogesh Kumar Yadav
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I was looking into the Singleton class code where double checked locking was handled .....
In this at Line 1 -- synchronized(Singleton.class) is used ...

What exactly this Line do ? Cant we use synchronize(this) here ??


public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
if (instance == null) //2
instance = new Singleton(); //3
}
}
return instance;
}
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's just like with static members. They're once per class, unlike instance members which are once per instance.

So, synchronized(this) only synchronizes on the current instance. That means if thread 1 calls method1 on instance1 and another thread calls method1 on instance2, they both will run concurrently. If you use ClassName.class the synchronization holds for whatever context from which an action is performed on a class.
 
Costi Ciudatu
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
synchronized(this) is simply illegal in this context, since you're in a static method, so there's no 'this'.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Costi Ciudatu wrote:synchronized(this) is simply illegal in this context, since you're in a static method, so there's no 'this'.


true. in this case you can only synchronize on other static members or on classes
 
Yogesh Kumar Yadav
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the Response ......

my mistake obviously we cannot use this here .....

Can you please elaborate this statement :
If you use ClassName.class the synchronization holds for whatever context from which an action is performed on a class.


Appreciate your help guys ..!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!