• 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

Problem in synchronized

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

Please go through the code block given below. Can somebody expalin the difference between these code blocks.

Thanks in advace
Anupam
*********************************************************************




[HENRY: Added code tags and disabled smilies]
[ August 26, 2006: Message edited by: Henry Wong ]
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The first will wait forever, because noone can notify the monitor.

Also, in the first example the synchronized block doesn't do anything, because no other thread could possibly enter the synchronized block using the same monitor.
[ August 26, 2006: Message edited by: Ilja Preuss ]
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ilja, I think you're overly tough on the first example. It needs to synchronise, so that it can wait(). However, see below.

The first one looks as if its purpose is to block, consuming no CPU, until the thread is interrupted. That's a valid thing to want to do. However, there is no need to synchronise and wait(). You can just Thread.sleep().

The second one has a classic bug, I think. The synchronize should be outside the loop, otherwise there are brief periods when a notification could be missed.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Peter Chase:
Ilja, I think you're overly tough on the first example. It needs to synchronise, so that it can wait().



True. I also didn't remember that a wait can also be stopped by interrupting the thread.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic