4

Yes, this is similar to onSpinWait​() method of Thread class - Java 9, but a little more nuanced...

static boolean isPrime(long candidate) {
    if ((candidate & 1) == 0)  // filter out even numbers
        return (candidate == 2);  // except for 2

    var limit = (long) Math.nextUp(Math.sqrt(candidate));

    for (long divisor = 3; divisor <= limit; divisor += 2) {
        Thread.onSpinWait(); // TODO is this a good practice in this context?
        if (candidate % divisor == 0) return false;
    }
    return true;
}

The javadoc for Thread.onSpinWait() says

Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities. By invoking this method within each iteration of a spin-wait loop construct, the calling thread indicates to the runtime that it is busy-waiting. The runtime may take action to improve the performance of invoking spin-wait loop constructions.

However, in my use case, this is not exactly busy-waiting, this is actually doing useful work. My intention with Thread.onSpinWait() is to give a hint to the JVM to inject some optimization if possible.

In testing, using Thread.onSpinWait() definitely incurs a huge performance penalty, but is there any reason to believe it might benefit other Threads running in the same JVM, the same O/S? For example, does using Thread.onSpinWait() offer some kindness to other threads? For example, does this push my thread/task to the background or change its priority, without having to resort to thread priority management

I suppose I could test for this, but that would be a difficult thing to test for...

Without knowing what the JVM specifically does with this hint, it's hard for me to reason about...

Eric Kolotyluk
  • 1,958
  • 2
  • 21
  • 30
  • 1
    I kind of wanted to know that also [a while ago](https://stackoverflow.com/questions/56056711/threadyield-vs-threadonspinwait). To be honest, the answer and the comments, proved once again that this is for the extreme pros, only. – Eugene Nov 04 '21 at 16:27
  • uh hu - sometimes it's nice to peek under the hood, but sometimes is scary too... – Eric Kolotyluk Nov 04 '21 at 16:43

0 Answers0