Field field = Shutdown.class.getDeclaredField("hooks");
field.setAccessible(true);
HashSet hooks = (HashSet) field.get(null);
for (Iterator it = hooks.iterator(); it.hasNext(); ) {
Thread hook = it.next();
Runtime.getRuntime().removeShutdownHook(hook);
it.remove();
}
public class WeakRunnable implements Runnable {
WeakReference weakRef;
public WeakRunnable(Runnable runnable) {
weakRef = new WeakReference<>(runnable);
}
@Override
public void run() {
Runnable runnable = weakRef.get();
if (runnable != null) {
runnable.run();
}
}
}
在代码中注册ShutdownHook时,可以使用该对象进行包装:
Runtime.getRuntime().addShutdownHook(new Thread(new WeakRunnable(() -> {
// Your code here
})));