天天看點

通過反射的方式注入自己的ShutdownHook并清除其他HOOK

String className = "java.lang.ApplicationShutdownHooks";

Class<?> clazz = Class.forName(className);

Field field = clazz.getDeclaredField("hooks");

field.setAccessible(true);

Thread shutdownThread = new Thread(new Runnable() {

    @Override

    public void run() {

        // TODO

    }

});

shutdownThread.setName("My-WebShutdownThread");

IdentityHashMap<Thread, Thread> excludeIdentityHashMap = new ExcludeIdentityHashMap<>();

excludeIdentityHashMap.put(shutdownThread, shutdownThread);

synchronized (clazz) {

    IdentityHashMap<Thread, Thread> map = (IdentityHashMap<Thread, Thread>) field.get(clazz);

    for (Thread thread : map.keySet()) {

        Log.info("found shutdownHook: " + thread.getName());

        excludeIdentityHashMap.put(thread, thread);

    field.set(clazz, excludeIdentityHashMap);

}

本文轉自 小眼兒 部落格園部落格,原文連結:http://www.cnblogs.com/hujunzheng/p/8573216.html,如需轉載請自行聯系原作者

繼續閱讀