Archive for the ‘Java/Spring’ Category

h1

Custom ThreadPoolExecutor

February 4, 2010

If your application is multithreaded and you use Java 6.0, most likely you will use ThreadPoolExecutor. The ThreadPoolExecutor class is a concrete implementation of the ExecutorService interface, which should be sufficient for most applications. It also provides useful hookup methods (like beforeExecute, afterExecute, etc) which can be overridden for customization purposes.

Here are the signatures:

protected void beforeExecute(Thread t, Runnable r);

protected void afterExecute(Runnable r, Throwable t);

As you can see, one of the parameters is Runnable. But what if you want to submit a Callable to your custom ThreadPoolExecutor?

Simply override these methods:

@Override
public void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);

if  (t==null && r instanceof  Future<?>) {

try {

String retValue =  (Future<?>)r.get(); // if your Callable returns a String

// add your code here

} catch (InterruptedException ie) { // handle it here}

catch (ExecutionException ee) { // handle it here}

catch(CancellationException ce) {// handle it here}

catch(Exception ex) { //handle it here}

}

You can inject an Observer into your custom ThreadPoolExecutor and either return retValue to the observer or notify it about any exceptions thrown. Make sure your observer is thread safe, especially methods you will invoke from your custom ThreadPoolExecutor. Happy threading!!!

Follow

Get every new post delivered to your Inbox.