Skip navigation

Monthly Archives: February 2012

//————————————————————–
// TIMED RUN – Interruption policy
//————————————————————–
//Impl A
//Start a new thread and cancel it one second after

List<BigInteger>aSecondOfPrimes()throwsInterruptedException {
PrimeGeneratorgenerator=newPrimeGenerator();
newThread(generator).start();
try{
SECONDS.sleep(1);
}finally{
generator.cancel();
}
return generator.get();
}

// :=( Cannot catch unchecked exception thrown from the new thread

//————————————————————–
//Impl B
privatestaticfinal ScheduledExecutorServicecancelExec= …;
public static void timedRun(Runnabler,longtimeout,TimeUnitunit) {
final Thread taskThread=Thread.currentThread();//Get the Thread object for later interuption
cancelExec.schedule(newRunnable() {
public void run() { taskThread.interrupt(); }
}, timeout, unit);
r.run();// Unchecked exception can be caught by the caller of timedRun
}
// :=( Try to interrupt a thread without knowing its interruption policy
// The task can complete before it gets interrupted
// Then the caller of timedRun will get interrupted
// :=( If the task is not reponsive when interrupting it will never return to the caller
//——————————————————————
publicstaticvoidtimedRun(finalRunnabler,
longtimeout,
TimeUnitunit)
throwsInterruptedException {
classRethrowableTask implementsRunnable{
private volatile Throwable t;
public void run() {
try{r.run(); }
catch(Throwablet) {this.t=t; }
}
void rethrow() {
if(t !=null)
throw launderThrowable(t);//rethrow if any
}
}
Rethrowable Task task = new RethrowableTask();
final Thread taskThread = newThread(task);
taskThread.start();
cancelExec.schedule(newRunnable() {
public void run() {taskThread.interrupt(); }
}, timeout, unit);
taskThread.join(unit.toMillis(timeout));// This makes sure rethrow happens once task completed
task.rethrow();
}

Follow

Get every new post delivered to your Inbox.