• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized()

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In that simple code , It is used :synchronized(this) , "this" is a reference to the current object.

My question is :

When lock of another object is used in synchronized()?
 
Siva Masilamani
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

let say you have ArrayList declared where it can be accessed by multiple thread which you want to avoid.

So in that case you can use lock on ArrayList
e.g



In the above code the lock is obtained on ArrayList Object not the Object that contains ArrayList.

Ofcourse it is just an example,but answer to your question is,it depends on design.

So the basic concept is use Synchronized block where you want to protect particular data(in this case ArrayList) from multiple access not the whole Object that contains the data.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!