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

Synchronization  RSS feed

 
Yuvi Gupta
Greenhorn
Posts: 20
C++ Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guyz,
i have a question regarding synchronized block.
Case 1:
class MyClass {

public void getSum(){
synchronized(this) {
}
}
}

Case 2:
class MyClass {
Object obj = new Object();

public void getSum(){
synchronized(obj) {
}
}
}


My question is what is the difference between synchronized(this) and synchronized(obj) , which one is better and where to use?
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yuvi Gupta wrote:My question is what is the difference between synchronized(this) and synchronized(obj)

In the example you gave: nothing. If you had more than one "obj" you could synchronise on, that would be different.

which one is better and where to use?

There's no real "better" or "worse" in cases like this; you should use whatever is applicable. However, as a general rule, I tend to prefer synchronized methods to synchronized(this) blocks.

Why? Because they're self-documenting, providing useful information to users of your class.

Just FYI, there are now ReentrantLock's, which offer quite a bit more control than simple lock objects and synchronized, so you might want to read up on them.

Winston
 
Yuvi Gupta
Greenhorn
Posts: 20
C++ Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Winston
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yuvi Gupta wrote:Thank you so much Winston

You're most welcome.

Winston
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!