Java高并发编程学习--16. 线程的UncaughtExceptionHandler

一、捕获UncaughtException

package p119_uncaught_exception_handler;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName CaptureThreadException
 * @Description TODO
 * 1. ThreadGroup如果有父ThreadGroup,则直接调用父Group的uncaughtException方法。
 * 2. 如果设置了全局默认的UncaughtExceptionHandler,则调用uncaughtException方法。
 * 3. 若既没有父ThreadGroup,也没有设置全局默认的UncaughtExceptionHandler,则会
 * 直接将异常的堆栈信息定向到System.err中。
 * @Author Cays
 * @Date 2019/5/4 10:01
 * @Version 1.0
 **/
public class CaptureThreadException {
    public static void main(String[] args) {
        // 1. 设置回调接口
        Thread.setDefaultUncaughtExceptionHandler((t,e)->{
            System.out.println(t.getName()+" occur exception");
            e.printStackTrace();
        });
        final Thread thread = new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            // 2. 这里出现unchecked异常
            System.out.println(1/0);
        },"t1");
        thread.start();
    }
}

结果:
在这里插入图片描述

二、java向程序注入Hook线程

  • Java向程序注入Hook线程,程序结束时调用。
package p119_uncaught_exception_handler;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName ThreadHook
 * @Description TODO
 * java向程序注入Hook线程
 * @Author Cays
 * @Date 2019/5/4 10:12
 * @Version 1.0
 **/
public class ThreadHook {
    public static void main(String[] args) throws InterruptedException {
        // 1. 向程序注入Hook
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                try {
                    System.out.println("The hook thread 1 is running.");
                    TimeUnit.SECONDS.sleep(1);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println("The hook thread 1 will exit.");
            }
        });
        // 2. 钩子线程可以注册多个
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                try {
                    System.out.println("The hook thread 2 is running.");
                    TimeUnit.SECONDS.sleep(1);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println("The hook thread 2 will exit.");
            }
        });
        System.out.println("The program will be stopping.");
    }
}

结果:
在这里插入图片描述

三、Hook防止某个程序被重复启动

package p119_uncaught_exception_handler;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName PreventDuplicated
 * @Description TODO
 * 1. 在开发中经常会遇到Hook线程,比如为了防止某个程序被重复启动,在进程启
 * 动时会创建一个lock文件,进程收到中断信号的时候会删除这个lock文件,在mysql
 * 服务器、zookeeper、kaa等系统中都能看到lock文件的存在,本例中,将利用hook线程
 * 的特点,模拟一个防止重复启动的程序。
 * 2. Hook线程应用场景以及注意事项
 * (1) Hookk线程只有在收到退出信号的时候会被执行,如果在kill的时候使用了参数.9,
 * 那么Hook线程不会得到执行,进程将会立即退出,因此.lock文件将得不到清理
 * (2) Hookk线程中也可以执行一些资源释放的工作,比如关闭文件句柄、socket链接、数
 * 据库connection等。
 * (3) 尽量不要在Hook线程中执行一些耗时非常长的操作,因为其会导致程序迟迟不能退出。
 * @Author Cays
 * @Date 2019/5/4 10:18
 * @Version 1.0
 **/
public class PreventDuplicated {
    public static final String LOCK_PATH="E:\\工作\\java学习\\imgs\\";
    public static final String LOCK_FILE=".lock";

    public static void main(String[] args) throws IOException {
        // 1. 注入Hook线程,在程序退出时删除lock文件
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("The program received kill signal.");
            getLockFile().toFile().delete();
        }));
        // 2. 检测是否存在.lock文件
        checkRunning();
        // 3. 简单模拟当前程序正在运行
        for (;;){
            try {
                TimeUnit.MILLISECONDS.sleep(10000);
                break;
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    private static void checkRunning() throws IOException{
        Path path = getLockFile();
        File file = new File(path.toUri());
        if (file.exists()){
            throw new RuntimeException("The program already running.");
        }
        // 如果不存在则创建
        file.createNewFile();
        file.setReadable(true);
        file.setWritable(true);
    }
    private static Path getLockFile(){
        return Paths.get(LOCK_PATH,LOCK_FILE);
    }
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值