Supongamos blockingMethod
simplemente dormir para algunos millis:
public void blockingMethod(Object input) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Mi solución es utilizar wait()
y synchronized
así:
public void blockingMethod(final Object input, long millis) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
blockingMethod(input);
synchronized (lock) {
lock.notify();
}
}
}).start();
synchronized (lock) {
try {
// Wait for specific millis and release the lock.
// If blockingMethod is done during waiting time, it will wake
// me up and give me the lock, and I will finish directly.
// Otherwise, when the waiting time is over and the
// blockingMethod is still
// running, I will reacquire the lock and finish.
lock.wait(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
así que se puede sustituir
something.blockingMethod(input)
a
something.blockingMethod(input, 2000)
espero que ayude.
Como referencia, echa un vistazo a Java concurrencia en la práctica por Brian Goetz pp 126 - 134, concretamente en la sección 6.3.7 "La colocación de los límites de tiempo en las tareas" ISN –