堆栈去哪里了:在线程池中寻找堆栈

public class RateLimiterDemo {
    public static class DivTask implements Runnable{
        int a,b;
        public DivTask(int a,int b){
            this.a = a;
            this.b = b;
        }
        @Override
        public void run(){
            double re = a/b;
            System.out.println(re);
        }
    }

    public  static void main(String[] args) {

        ThreadPoolExecutor pools = new TraceThreadPoolExecutor(0,
                Integer.MAX_VALUE,
                0L, TimeUnit.SECONDS,
                new SynchronousQueue());
        for(int i =0;i<5;i++)
            pools.execute(new DivTask(100,i));
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

public class TraceThreadPoolExecutor extends ThreadPoolExecutor {
    public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
                                   long keepAliveTime, TimeUnit unit,
                                   BlockingQueue workQueue){
        super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue);
    }
    @Override
    public void execute(Runnable task){
        super.execute(wrap(task,clientTrace(),Thread.currentThread().getName()));
    }
    @Override
    public Future submit(Runnable task) {
        return super.submit(wrap(task,clientTrace(),Thread.currentThread().getName()));
    }

    private Exception clientTrace(){
        return new Exception("Client stack trace");
    }

    private Runnable wrap(final Runnable task,final Exception clientStack,
                          String clientThreadName) {
        return new Runnable() {
            @Override
            public void run() {
                try{
                    task.run();
                } catch (Exception e){
                    clientStack.printStackTrace();
                    try {
                        throw e;
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        };
    }
}

如果使用线程池,那么错误可能会变得更加常见。
wrap方法得第2个参数为一个异常,里面保存着提交任务得线程堆栈信息。该方法将我们
传入的Runnable任务进行一层包装,使之能处理异常信息。当任务发生异常时,
这个异常会被打印。
堆栈去哪里了:在线程池中寻找堆栈_第1张图片

你可能感兴趣的:(java,android,servlet)