Hi Everyone, I have a question on the following piece of code:
Assuming that thread A is the caller of this code, am I correct in thinking that things happen in the following order? : 1) Thread A acquires the lock for this monitor upon entering the synchronized method. 2) The call to notify() causes, let's say Thread B, to go into the seeking lock state. 3) Thread A exits the synchronized method and releases the lock. 4) Thread B acquires the lock and continues whereever it left off. Just wanted to make sure. Thanks. Mansi [ Jess added UBB [code] tags to preserve whitespace ] [ October 31, 2002: Message edited by: Jessica Sant ]
I am not really sure about this but still I will try to guess it, SOMEONE PLEASE CORRECT ME IF I AM WRONG : About step 4, I think there is no guarantees that thread B will be the one who will be acquiring the lock on that object again. What if there is some other thread of higher priority.
I think there is a typo, request must be assigned true before notify(). Otherwise the threads will wait forever. Doing so this code acts like a latch, once it is set to true all the waiting threads are waked up, and the next invoking threads are not waiting anymore. All the calling threads will be waiting untill one of them is interrupted, then that thread will continue by making request to true an notifying another waiting thread, which again will execute the assignment to request and notify call. All the waiting threads will be waked up. The next invoking threads will not wait because request is true and the extra calls to notify make no harm.
Instead of calling interrupt any other invoking thread will also release the latch. Anyway the variable request could be declared volatile to ensure visibility of the change made to it.