Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

JQ+ Mock - Threads - Question ID: 988384270281

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all, this is from JQ+ Mock Question ID: 988384270281

The answer given is: Here, there are two threads. But when one thread enters run(), it accquires lock on obj and enters into infinite loop. Now, the second thread also enters run but has to wait as it is also trying to accquire the same lock (obj is a static field). So, in affect, only the thread that gets the lock first, keeps on running. The second thread never gets a chance. so the values printed are sequencial, x and y are always printed as equal and they get incremented by 1 on each line.



However, when I tried removing the "static" on line 04, I could see that both threads are shown in the println on line 13. why is it that "x" and "y" are still incrementing by 1 on each line (which suggests to me that syncronization still works) but both threads are shown eventhough we have an infinite loop (which suggests to me that syncronization doesn't seem to work). The screen output I got is:



instead of:


[ August 07, 2006: Message edited by: Shanel Jacob ]
 
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the first case (when you have used static), class lock has to be obtained to enter into synchronized block.

And in second case (without static), its object lock and you have two seperate objects. So, both threads didn't interfere with each other's execution.
[ August 07, 2006: Message edited by: Kishore Balla ]
 
Kishore Balla
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
~ edited ~

[repeated]
[ August 07, 2006: Message edited by: Kishore Balla ]
reply
    Bookmark Topic Watch Topic
  • New Topic