Advantages of the hook method:
beforeExecute(Thread, Runnable) and afterExecute(Runnable, Throwable)
beforeExecute(Thread, Runnable ) and afterExecute(Runnable, Throwable) , which are called before and after each task. They can be used to control the runtime; e.g. reinitializing ThreadLocals, collecting statistics, or adding log entries
I am using Custom ThreadPoolExecutor to handle uncaught exceptions. I can add try{} catch{} blocks to Runnable and Callable , but suppose a scenario in which you cannot force the developer to add these blocks to the corresponding Runnable and Callable tasks.
This CustomThreadPoolExecutor , overrides the afterExecute () method in ThreadPoolExecutor , as shown below (I assigned the value of the b Zero variable to simulate an arithmetic exception.
import java.util.concurrent.*; import java.util.*; class CustomThreadPoolExecutor extends ThreadPoolExecutor { public CustomThreadPoolExecutor() { super(1,10,60,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(1000)); } protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if (t == null && r instanceof Future<?>) { try { Object result = ((Future<?>) r).get(); System.out.println(result); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt();
Since submit() hides an exception in the framework, I have an overridden afterExecute() method for catch Exception.
In this method, I added a blocking call with the instruction below
Object result = ((Future<?>) r).get();
I currently have 10 threads with a queue size of 1000. Suppose my Runnable takes 5 seconds.
Overriding the afterExecute () method, are there any performance overheads or any disadvantages of this approach?