Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
Is there any benefit to Thead.onSpinWait() while doing CPU Bound work?

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...

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!