Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda