Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda