• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question regarding Synchronized(anObject)  RSS feed

 
Simon Good
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Would someone confirm that this block of code doesn't really serve any purpose?

I'm of the opinion that creating the Object 'sync' and then synchronising on it is pointless since the object is local to the method.
From what I've learnt (from doing the JSCD) the Object 'sync' needs to be a class member. FYI There's only one instance of this class, the class is acting as a connection pool. Ignore the 'wait(100)' I'll replace that with a wait() and add a notify where it's required.
Of course I may have lost the plot completely in which case can someone tell me why the code is perfectly fine.
Thanks in advance for any response
[ August 11, 2003: Message edited by: Jim Yingst ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems pretty weird, but you never know -- sometimes dumb looking code turns out to be smart...
One thing is for certain: the wait() will always last for 100 milliseconds, unless another thread calls interrupt(); no-one will ever call notify().
Perhaps that's the point. The author of this code seems to be using wait(100) as a substitute for Thread.sleep(100), maybe not realizing that interrupt() will interupt sleep() just as it interrupts wait().
On the other hand, the synchronized block also serves as a memory barrier, and so maybe they have a vague idea about propagating memory contents across threads, and are trying to kill two birds with one stone? In that case, it's the opposite of "programming by intention," it's "try something and see what happens."
Anyway, I think I'd replace the whole synchronized block with a call to Thread.sleep(100), which expresses the intent much more clearly.
[ August 11, 2003: Message edited by: Ernest Friedman-Hill ]
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
100 seconds -> milliseconds
Yup. A simple call to Thread.sleep() would be much more straightfoward
 
Dana Hanna
Ranch Hand
Posts: 227
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll bet that the original programmer did not know about Thread.sleep(). The synchronized block is there because it's required by wait().
I've seen worse substitutes for Thread.sleep():
for (int i=0;i<100000;i++);
AAAAAAAAAAAHHHHHHHHHHHHHHH.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!