Runtime.getRuntime().addShutdownHook()

解决 the application appears to have started a thread ... but failed to stop it, this is very likely to create a memory leak.这个警告

RunTime.getRunTime().addShutdownHook的作用就是在JVM销毁前执行的一个线程.当然这个线程依然要自己写.

JDK提供了Java.Runtime.addShutdownHook(Thread hook)方法,可以注册一个JVM关闭的钩子,这个钩子可以在一下几种场景中被调用:

  1. 程序正常退出
  2. 使用System.exit()
  3. 终端使用Ctrl+C触发的中断
  4. 系统关闭
  5. OutOfMemory宕机
  6. 使用Kill pid命令干掉进程(注:在使用kill -9 pid时,是不会被调用的)

有时候我们用到的程序不一定总是在JVM里面驻守,可能调用完就不用了,释放资源.

利用这个性质,如果我们之前定义了一系列的线程池供程序本身使用,那么就可以在这个最后执行的线程中把这些线程池优雅的关闭掉.

    @Test
    public void testClose() {
        initCloseEvent();
        System.out.println("----");
    }

    /**
     * 在JVM销毁前执行的一个线程
     */
    private void initCloseEvent() {
        ScheduledExecutorService monitorSchedule = new ScheduledThreadPoolExecutor(
                1, new ThreadFactoryBuilder().setNameFormat(
                "import-user-thread-pool").build(),
                new ThreadPoolExecutor.AbortPolicy());
        monitorSchedule.scheduleWithFixedDelay(this::importUerInfo, 0, 1, TimeUnit.HOURS);

        Runtime.getRuntime().addShutdownHook(new Thread("do-when-jvm-is-shut-down") {
            @Override
            public void run() {
                monitorSchedule.shutdown();
                System.out.println("shutdown program");
            }
        });
    }

    private void importUerInfo() {
        System.out.println("import user");
    }

Runtime.getRuntime().addShutdownHook()_第1张图片

警告日志图,当时看到这个还不知道可以这么干,

 

你可能感兴趣的:(java)