Sahil
Sahil

Reputation: 96

Why yield method in java does not release the lock?

I have some doubt regarding the yield method in java. Because when we are using it like Thread.yield() then the thread goes to the runnable state and give chance to the other thread to run but the thread which call yield is not releasing the lock. So , only threads except those who are waiting for the lock to release will run . So , when and in which scenario this yield method is useful.

Upvotes: 1

Views: 981

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27125

I agree with @kdgregory, Thread.yield() probably should not be used in modern Java programs. But, it's not because allowing one thread to yield to others is a bad idea: It's just because, if you really need to yield(), then you probably are re-inventing an algorithm that is already implemented in java.util.concurrent.


One thing's for sure: If you're going to yield(), don't do it inside a synchronized block. The whole point of yield() is to let other threads run. The whole point of a synchronized block is "I want to finish this bit before any other thread gets to start it."

Your goal should always be to make sure your program spends as little time in synchronized blocks as possible. The more time it spends in synchronized blocks, the less it will benefit from multiple processors. Every synchronized block is a bottleneck. Even a small one can make a big difference. Read about Amdahl's Law.

Upvotes: 1

kdgregory
kdgregory

Reputation: 39606

Thread.yield() is useful in an environment that provides co-operative rather than pre-emptive threading. In other words, if the OS will not suspend your thread to let another run. In such an environment, you should regularly call yield() when performing a CPU-intensive operation.

I don't know of any modern operating systems that support Java but don't support pre-emptive threading, so it has little/no use in modern Java programs.

Thread.yield() has nothing to do with locks, is not documented to affect locks in any way, and should not be used in the assumption that it will release a lock.


Edit: this SO answer has much more information on how Thread.yield() is implemented (at least as-of JDK 1.6).

Upvotes: 4

Related Questions