Handling Task Rejections – Java’s Executor/Spring’s TaskExecutor
Are you seeing exceptions like TaskRejectedException(Spring Framework) or RejectedExecutionException(Java), and you want my few cents on how to handle it, go ahead plz.
The easiest way, though not the best way, is to use ThreadPoolExecutor.CallerRunsPolicy as a RejectionExecutionHandler for thread pool scenarios with BOUNDED queue.
By default, the Executor uses the Abort Policy, which just throws an exception, if all the threads in the pool are busy with tasks. If we explicitly specify CallerRuns policy, the Executor uses the main process to execute the newest task when all threads are busy.
Looks great huh! But there’s a prob with this – Application Performance may get affected if main process is held up with that task.
Hmm.. another way, less of work is to use an UNBOUNDED queue. Obviously, you know what’s the downside with this.
Hmm.. or, if it’s really complicated, try the concept of custom-written SEMAPHORES. Hope you can google and know about this approach. This is my cent: http://www.theschlock.com/blog/?p=178. Have a look at it.