• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized code block  RSS feed

 
Maulik Pokiya
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, I am appearing for scjp. In many codes I had seen synchronized() code blocks. but I don't know what's the diff. between all these.
please help me that what is the diff between all foll. syntaxes of synchronized() and any other.

synchronized(System.out) {}

synchronized(new String("a")) {}

synchronized("A") {}

synchronized(this) {}

synchronized(Thread.currentThread()) {}
 
Stephan van Hulst
Saloon Keeper
Posts: 7817
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are not different syntaxes. They all do the same thing, they use the object given as a lock.

*Never* use synchronized(new <constructor call>) {}, and *never* use synchronized(Thread.currentThread()) {}.

The first one will always lock on a new object, which makes it useless. The second one will always lock on the thread running the synchronized code, which will always acquire the lock, which makes it useless.

synchronized(this) {} happens often, and is very useful. Synchronizing on System.out and on "A" should technically work, but they may make the code less readable. Synchronizing on System.out may have its uses, but "A" never makes sense.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Syntacticly there is no difference between those. The only difference is on the Object the lock is held on. Look through the Objects and see why you would or would not use each one.
 
Maulik Pokiya
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to Stephen van Hulst and Steve Luke for helping me it will sure going to help me a lot!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!