2010-04-25 4 views

Respuesta

5

Thread.isInterrupted() es una función muy barata para llamar. Hay algunas indirecciones más, pero todas las llamadas son lo suficientemente rápidas. Para resumir:

Debe ser posible para Java para emular Thread.currentThread().isInterrupted() realizando el indirecto doble Thread::current()->_osthread->_interrupted.

Source:

bool os::is_interrupted(Thread* thread, bool clear_interrupted) { 
    assert(Thread::current() == thread || Threads_lock->owned_by_self(), 
    "possibility of dangling Thread pointer"); 

    OSThread* osthread = thread->osthread(); 

    bool interrupted = osthread->interrupted(); 

    if (interrupted && clear_interrupted) { 
    osthread->set_interrupted(false); 
    // consider thread->_SleepEvent->reset() ... optional optimization 
    } 

    return interrupted; 
} 

OSThread se implementa como esto:

volatile jint _interrupted;  // Thread.isInterrupted state 

// Note: _interrupted must be jint, so that Java intrinsics can access it. 
// The value stored there must be either 0 or 1. It must be possible 
// for Java to emulate Thread.currentThread().isInterrupted() by performing 
// the double indirection Thread::current()->_osthread->_interrupted. 
.... 
volatile bool interrupted() const     { return _interrupted != 0; } 
0

El método isInterrupted se usa para verificar si el hilo está interrumpido o no y no afecta el rendimiento. Además, no se restablece si el hilo ya se ha interrumpido. también consulte los siguientes enlaces: link text

link text

1

No sé si se adquiere un bloqueo o no, pero me encontré con una prueba rápida y para mí isInterrupted() es aproximadamente 100 veces más lento que la lectura de una variable volátil . Ahora bien, si importaría o no en su aplicación, no puedo decírselo.

+0

¿Podría publicar el punto de referencia que utilizó? –

+0

@Michael: Hice una prueba muy cruda. Básicamente, solo se repite unos pocos millones de veces y en el bucle se llama Interrumpido() para la primera prueba y se lee la variable para la segunda. No hay otros hilos involucrados. También guardé una referencia al valor para que el bucle no se optimizara. – JRL

+0

¡Cuidado con los micro-puntos de referencia! Especialmente en una JVM. Hay muchos factores que pueden sesgar fácilmente los resultados. Lo ideal es implementar esto en su aplicación y probarlo de verdad. Más detalles en http://www.ibm.com/developerworks/java/library/j-jtp02225.html. – mdma

Cuestiones relacionadas