3

I can find old references and SO answers that say the behavior of Thread.yield() varies by platform. This answer indicates that that's because the behavior isn't actually specified.

Is it still the case with modern versions of Java that Thread.yield() behavior varies by platform?

Edit

I've already read the documentation. I understand what it implies. I'm asking about actual behavior.

Community
  • 1
  • 1
G. Ann - SonarSource Team
  • 22,346
  • 4
  • 40
  • 76

2 Answers2

5

From the Java 8 API (latest non-beta to date):

A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.

It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

The implications are:

  • Yes, still platform-dependent
  • Yes, heuristic
Mena
  • 47,782
  • 11
  • 87
  • 106
2

Even if the exact details of Thread.yield() behavior are different on different platforms, the method call still basically does nothing.

You call it, and it does nothing, and it returns as quickly as possible modulo the fact that it either may or may not end the thread's current time slice.

Is it a "cross-platform minefield?"

If you write code that won't work unless Thread.yield() actually does end the caller's time slice, then you have written platform-specific code. But, Java probably should not be your language of choice if you need platform-specific behavior.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
  • 2
    Yielding isn't an anachronism. Believe it or not, not all cores on all processors are devoted fully to your application. Yield still has its uses. I agree it isn't a minefield, but it has a purpose. – Gabe Sechan Aug 16 '16 at 19:30