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

Is there any difference between synchronized(this) and synchronized(className.class)?  RSS feed

 
Angel Jordan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Can somebody please tell me if there is any difference between synchronized(this) and synchronized(className.class)?

Thanks!
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angel Questions wrote:Can somebody please tell me if there is any difference between synchronized(this) and synchronized(className.class)?


You mean, besides the obvious, that they are two different objects?

Henry
 
Angel Jordan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
E.g
method1(){
synchronized(this){
---some code
}
}

method2(){
synchronized(test.class){
---some code
}
}

now I'm calling the above methods like
obj1.method1(); - will it create a lock on obj1??

obj1.method2(); - will it create a lock on test class??
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angel Jordan wrote:
now I'm calling the above methods like
obj1.method1(); - will it create a lock on obj1??



It will grab the lock for the instance used to call method1(). If another thread tries to grab the same lock, it will block.

Angel Jordan wrote:
obj1.method2(); - will it create a lock on test class??


It will grab the lock for the class object for the class. If another thread tries to grab the same lock, it will block.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!