Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does thread.yield() lose the lock on object if called inside a synchronized method?

I understand that Thread.currentThread().yield() is a notification to thread scheduler that it may assign cpu cycle to some other thread of same priority if any such is present. My question is: If current thread has got lock on some object and calls yield(), will it loses that lock right away? And when thread scheduler finds out there is no such thread to assign cpu cycle, then the thread which has called yield() will again be in fight to get lock on the object which it has lost earlier??

I couldn't find it in javadoc and forums [http://www.coderanch.com/t/226223/java-programmer-SCJP/certification/does-sleep-yield-release-lock] have 50-50 answers.

I think yield() (lets say thread1) should release lock because if some thread (lets say thread2) of same priority wants to operate on same object, then it can have chance when thread scheduler eventually assign cup to thread2.

like image 680
Amaresh Avatar asked May 21 '12 04:05

Amaresh


People also ask

What happens when thread's yield () method is called?

Thread. yield method gives hint to the thread scheduler that it is ready to pause its execution. The thread scheduler is free to ignore this hint. If any thread executes the yield method, the thread scheduler checks if there is any thread with the same or high priority as this thread.

Is lock required for synchronized method?

If a thread wants to execute a synchronized method on a given object, first it has to get a lock of that object. Once thread got the lock then it is allowed to execute any synchronized method on that object.

What happens when synchronized object is invoked?

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

What will happen if a synchronized method is called by two threads on different object instances simultaneously?

No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.


1 Answers

No. Thread.yield() is not like Object.wait(). It just gives up control to allow a thread switch. It will have no effect on the concurrency of your program.

There is no guarantee which thread the scheduler will run after a yield.

like image 105
Francis Upton IV Avatar answered Sep 23 '22 03:09

Francis Upton IV