All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.huaweicloud.dis.util.JstackUtils Maven / Gradle / Ivy

The newest version!
package com.huaweicloud.dis.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;

/**
 * 打印堆栈线程
 */
public class JstackUtils {
    private static final Logger LOG = LoggerFactory.getLogger(JstackUtils.class);
    private static final Map cache = new ConcurrentHashMap<>();
    private static final ScheduledExecutorService exe = Executors.newScheduledThreadPool(1);

    static {
        Thread thread = new Thread(() -> cleanup(), "jstackUtils-Thread");
        thread.setDaemon(true);
        thread.start();
    }

    public static void put(Thread thread, long requestConnectionTimeOut) {
        long requestExpireTimeout = requestConnectionTimeOut + 5000;
        cache.put(thread, System.currentTimeMillis() + requestExpireTimeout);
    }

    private static void cleanup() {
        while (true) {
            long now = System.currentTimeMillis();
            // find expired requests
            List expired = cache.entrySet().stream()
                    .filter(e -> e.getValue() < now)
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());

            expired.forEach(t -> {
                printStackTrace(t);
                sleep(2000);
                printStackTrace(t);
                cache.remove(t);
            });
            sleep(3000);
        }
    }

    public static void remove(Thread thread) {
        cache.remove(thread);
    }

    private static void printStackTrace(Thread thread) {
        StringBuilder builder = new StringBuilder();
        builder.append("DIS Request is exception, thread stack detail: \n");
        builder.append(thread.getThreadGroup()).append("     threadState: ")
               .append(thread.getState()).append("\n");
        for (StackTraceElement element : thread.getStackTrace()) {
            builder.append("    ").append(element.toString()).append("\n");
        }
        LOG.warn(builder.toString());
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy