Asynchronous Executor
20 Feb 2009I hate that sometimes I have to make calls to systems outside of my own system, essentially outside of my own control. And not all of these calls allow me to detect and recover when an operation is taking longer than it should.
So I’ve written a class that allows you to execute a task asynchronously and give it a maximum time to run, and you get a callback upon completion or upon failure. Now I can detect and recover when things happen that are outside of my control.
package com.peterfranza.synchro;
public class AsyncExecutor {
private static java.util.concurrent.ExecutorService pool =
java.util.concurrent.Executors.newCachedThreadPool();
public synchronized static void asyncExecuteTask(
final Runnable task,
final long timeout,
final AsyncExecutorCallback callback) {
pool.execute(new Runnable() {
@Override
public void run() {
java.util.concurrent.Future<AsyncExecutorCallback> marker =
pool.submit(task, callback);
try {
marker.get(timeout,
java.util.concurrent.TimeUnit.MILLISECONDS)
.taskCompleted();
} catch (Exception e) {
marker.cancel(true);
callback.taskFailed();
}
}
});
}
public interface AsyncExecutorCallback {
void taskCompleted();
void taskFailed();
}
}
Usage
package com.peterfranza.synchro;
import com.peterfranza.synchro.AsyncExecutor.AsyncExecutorCallback;
public class Usage {
public static void main(String[] args) {
AsyncExecutorCallback callback = new AsyncExecutorCallback() {
@Override
public void taskCompleted() {
System.out.println("Task Completed");
}
@Override
public void taskFailed() {
System.out.println("Task Failed");
}
};
AsyncExecutor.asyncExecuteTask(new QuickTask(), 1000, callback);
AsyncExecutor.asyncExecuteTask(new LongTask(), 1000, callback);
}
private static class QuickTask implements Runnable {
public void run() {
try {Thread.sleep(10);}
catch(Exception e){}
}
}
private static class LongTask implements Runnable {
public void run() {
try {Thread.sleep(100000);}
catch(Exception e){}
}
}
}