Guifan Li Guifan Li - 11 months ago 75
Java Question

Java yield() a thread with synchronized block to a higher Priority thread also with a synchronized block.

From what I understand, yield() on a thread does not release the lock for that thread. So if there are two Threads and both of them have synchronized block in the thread pool, A with lower priority and B with higher priority. If Thread A is running and yield() is called in A, thread B now will run by scheduler. Because currently, thread A is still holding the lock, so thread B can not go into the critical block? From my understanding, this will cause a deadlock?

Please let me know do I miss something?

Thanks very much:)

Answer Source

There is some confusion here.

  1. There is no deadlock, because there is only one lock. You need at least two locks for a deadlock.

  2. yield() does essentially nothing. See the Javadoc.

  3. At any time, possibly including when you call yield(), the higher-priority thread will block trying to obtain the lock. So it is no longer eligible for execution. So the scheduler will have to schedule something else that is runnable.

  4. Meanwhile the lower-priority thread remains runnable (i.e. eligible for execution), so it will get scheduled sooner or later, so it continues to execute. Sooner or later it will release its lock, which will allow the higher-priority thread to acquire it and continue its execution.