• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

synchronized code block

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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()) {}
 
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!!!
 
reply
    Bookmark Topic Watch Topic
  • New Topic