1. 程式人生 > >多執行緒中異常堆疊資訊展示

多執行緒中異常堆疊資訊展示

在多執行緒中會出現異常情況發生, 但是又苦於沒有任何日誌資訊, 這對程式設計師來說拍錯是個致命的打擊, 不小心需要好幾天都沒有眉目
針對這種情況, 對JDK自帶的執行緒池進行改造, 讓其能夠顯示出對應的錯誤日誌,
建立TraceThreadPoolExecutor extends ThreadPoolExecutor (JDK自帶執行緒池)
import java.util.concurrent.*;


/**
 * Created by Luoqy on 2017/7/9 0009.
 */
public class TraceThreadPoolExecutor extends ThreadPoolExecutor {




    public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }


    @Override
    public void execute(Runnable task){
        super.execute(warp(task, clientTrace(), Thread.currentThread().getName()));
    }






    @Override
    public Future<?> submit(Runnable task){
        return super.submit(warp(task, clientTrace(), Thread.currentThread().getName()));


    }


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


    private Runnable warp(final Runnable task, final Exception clientStack, String clientThreadName) {


        return new Runnable() {
            @Override
            public void run() {
                try {
                    task.run();
                } catch (Exception e) {
                    clientStack.printStackTrace();
                    throw e;
                }
            }
        };
    }


以上warp()方法的第2個引數為一個異常資訊,裡面儲存提交任務的執行緒中的堆疊資訊, 該方法將我們傳入的Runnable任務進一步進行包裝, 使之能處理異常資訊,當異常發生時將會進行異常資訊列印


測試Demo展示:
建立一個除法運算的任務
public class DivTask implements Runnable {
    int a;
    int 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) {
        TraceThreadPoolExecutor pools = new TraceThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());


        for (int i = 0; i < 5; i++) {
            pools.execute(new DivTask(100, i));
        }


    }




執行之後你將看到錯誤提示資訊:


100.0
java.lang.Exception: Client stack trace
25.0
50.0
at com.beingmate.vip.controller.TraceThreadPoolExecutor.clientTrace(TraceThreadPoolExecutor.java:29)
33.0
at com.beingmate.vip.controller.TraceThreadPoolExecutor.execute(TraceThreadPoolExecutor.java:17)
at com.beingmate.vip.controller.TraceThreadPoolExecutor.main(TraceThreadPoolExecutor.java:51)
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at com.beingmate.vip.controller.DivTask.run(DivTask.java:17)
at com.beingmate.vip.controller.TraceThreadPoolExecutor$1.run(TraceThreadPoolExecutor.java:38)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)




備註:
 pools.execute() 和 pools.submit().get()方法也可以打印出部分堆疊資訊, 但是無法知道是哪個執行緒出現問題