Introduction
This is a continuation post on the exception handling strategies in the threads in Java.
For Introduction, please read this post
The second post is available here
This post addresses the problem statement "How to use the exception handlers in the threads spawned by the Executor Service in Java?"
Not all times, we will be using Thread classes to run our threads because we have to manage a lot of the underlying logic for managing threads. There is ExecutorService in Java which comes to the rescue for the above problem.
In the previous posts, we have discussed on how to handle the exceptions in plain threads. However, when using executor service, we do not create / manage threads, so how do we handle exception in this case.
We have a ThreadFactory as an argument which can be used to customize the way threads are created for use within the ExecutorService.
The below snippet of code leverages this feature to illustrate the exception handling, wherein we create a factory and internally we manage the thread and set its ExceptionHandler and allow the executor service to use this thread so that it can bring in threads with exception handlers customized.
class ExceptionHandlingThreadFactory extends NamedThreadFactory {
@Override
public Thread newThread(Runnable r) {
ct++;
Thread t = new Thread(r, format("%s%d", name, ct));
t.setUncaughtExceptionHandler((t1, e) -> System.out.println("Handling the exception in factory for thread: " + t1.getName() + " and exception is: " + e.getMessage()));
return t;
}
}
The above code illustrates the user of the Threadfactory (in the above case the NamedThreadFactory is actually implementing ThreadFactory as given below)
public class NamedThreadFactory implements ThreadFactory {
protected static int ct = 0;
protected String name = "My_NamedThread_";
@Override
public Thread newThread(Runnable r) {
ct++;
return new Thread(r, format("%s%d", name, ct));
}
}
Now, that we have the factories in place, how do we use them, below given snippet of code illustrates how it is done.
ExecutorService service = Executors.newCachedThreadPool(new ExceptionHandlingThreadFactory());
service.execute(new ExceptionLeakingTask());
Comments
Post a Comment