Wednesday, 29 June 2011

How to make your own Thread Pool

Following are the steps to create your own thread pool :
  • create your ThreadPoolExecutor that includes specific BlockingQueue and Comparator.
  • override the beforeExecute and afterExecute
  • create your ThreadFactory that implement uncaughtException to prevent thread dead problem
Creating the ThreadPoolExecutor

class MyThreadPoolExecutor extends ThreadPoolExecutor{
protected MyThreadPoolExecutor(){
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue(maxCapacity,new MyComparator()),new MyThreadFactory());
}
@Override
protected void beforeExecute(Thread t,Runnable r){
/*do your stuff*/
super.beforeExecute(t, r);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
/*do your stuff*/
super.afterExecute(r, t);
}

}

Creating our ThreadFactory:

class MyThreadFactory implements ThreadFactory {
private final MyThreadGroup tg = new MyThreadGroup();
public Thread newThread(Runnable r) {
return new Thread(tg,r);
}
}
private class MyThreadGroup extends ThreadGroup{
private MyThreadGroup(){
super("MyThreadGroup");
}
public void uncaughtException(Thread t, Throwable e){
log.debug(t);
/*do something*/
}
}

No comments:

Post a Comment