• Post Reply Bookmark Topic Watch Topic
  • New Topic

dumb question about thread

 
FY Hsieh
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for a "synchronized" method, if one thread is executing this method and at the same time another thread tries to call it too, what happens to the 2nd thread ? will it be alive but waiting until the 1st thread is done ? or will it be killed ? If it has to wait, is there a limition of how long it can wait ?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will wait forever until the locked object becomes free.
 
David Nemeskey
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need to specify a time limit, try wait() & notify(). The former has overloaded variants which accept a timeout value in milliseconds and nanoseconds.
[ November 20, 2006: Message edited by: David Nemeskey ]
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If Thread 1 runs in a synchronized method, it gets the lock for the object. If thread 2 tries to run the same synchonized method of the same object, then it will be blocked. It is still alive and still has the potential to run again.

I believe that when Thread 1 exits the synchronized method, then one of the threads that is waiting for the object that was locked will be automatically awakened. If there is more than one Thread waiting for the lock, then I believe that the one that is awakened is chosen at random.

-- Kaydell
 
Phil Meyer
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is more than one Thread waiting for the lock, then I believe that the one that is awakened is chosen at random.


Well, not necessarily at random, from what I've read, but in a way that isn't defined by the Java Spec, and is up to the particular JVM you are using. So you won't know which thread gets chosen next, it may be random, or it may be chosen by some criteria which you don't know about, and even if you did, you couldn't count on.

(correct me if I am wrong, of course)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!