Asynchronous Executor
I 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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){} } } } |
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.



Comments
No comments yet.
Leave a comment