Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Small Doubt on Threads

 
Vepa Sritej
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pls help me with this small doubt:

When notify() is called on an object will the thread waiting on the object comes to Runnable state immediately or will it come to runnable when the lock is released by the currently holding thread.

Pls help Thanks in advance
 
Henry Wong
author
Marshal
Pie
Posts: 21367
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vepa Sritej:
Pls help me with this small doubt:

When notify() is called on an object will the thread waiting on the object comes to Runnable state immediately or will it come to runnable when the lock is released by the currently holding thread.

Pls help Thanks in advance


The thread that got the notification doesn't immediately run -- it still has to reacquire the lock before it can return from the wait() method.

Of course, other issues (like priority) may also prevent it from running too.

Henry
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vepa,

I think the second is correct, the notified thread has to wait for the lock being released.
And notify() will not release the key, the thread calling notify has to leave the sync block first. If he's the one having that lock.

Api says about this:
java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#notify()
Second paragraph:
"The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object."


Yours,
Bu.
 
Vepa Sritej
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Burkhard,

thats what i thought but in one of the mock exams ive encountered a question stating " when will the thread enters the runnable state and the answer given is "when notify() is called". Im doubtful if this is an absolute answer.
 
Aniket Patil
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is assumed that you call notify() just before the end of your synchronized block. But again, it's not a canonical answer as explained above.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic