[ISSUE #4095] Code Optimization and Interrupeted Exception handling.

issue介绍

tag: first good issue

地址:github.com/apache/even...

Code Optimization and Interrupeted Exception handling in EtcdCustomService.class

对EtcdCustomService类的变量以及InterrupetedException处理的优化

知识点

Interrupeted Exception

大家先看下面这段代码:

1.创建一个Runnable类

Java 复制代码
public class InterruptedRunnable implements Runnable {
    @Override
    public void run() {
        Thread currentThread = Thread.currentThread();
        while(true){
            if(currentThread.isInterrupted()){
                break;
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2.运行的时候对它进行中断

Java 复制代码
public class Main {

    public static void main(String[] args) {
        InterruptedRunnable interruptedRunnable = new InterruptedRunnable();
        Thread interruptedThread = new Thread(interruptedRunnable);
        interruptedThread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        interruptedThread.interrupt();
    }

}

可以观察到两点:

1.Interrupted Exception

2.线程当前还在运行

上述代码明明调用了线程的interrupt()方法来中断线程,但是却并没有起到啥作用。原因是线程的run()方法在执行的时候,大部分时间都是阻塞在sleep(100)上,当其他线程通过调用执行线程的interrupt()方法来中断执行线程时,大概率的会触发InterruptedException异常。

如何正确处理Interrupeted Exception

在触发InterruptedException异常的同时,JVM会同时把线程的中断标志位清除,所以,这个时候在run()方法中判断的currentThread.isInterrupted()会返回false,也就不会退出当前while循环了。

处理InterruptedException异常时要小心,如果在调用执行线程的interrupt()方法中断执行线程时,抛出了InterruptedException异常,则在触发InterruptedException异常的同时,JVM会同时把执行线程的中断标志位清除,此时调用执行线程的isInterrupted()方法时,会返回false。此时,正确的处理方式是在执行线程的run()方法中捕获到InterruptedException异常,并重新设置中断标志位(也就是在捕获InterruptedException异常的catch代码块中,重新调用当前线程的interrupt()方法)。 我们在类的catch中进行一个中断标志位的设置

Java 复制代码
try {
    Thread.sleep(100);
} catch (InterruptedException e) {
    e.printStackTrace();
    currentThread.interrupt();
}

主线程就会运行结束:

pr过程中注意的事项

  1. fork到自己的仓库然后创建对应的分支解决问题 比如git checkout -b fix_patch_4508
  2. checkstyle一定要配置好,不然ci必报错(一个小空格都会报错),ci会检查你commit的文件
  3. 提PR的时候注意格式(标题、正文带解决的issue (Fixs #xxx))

参考对应的官方文档: eventmesh.apache.org/zh/communit...

------------开源小白 希望不断积累

相关推荐
用户094248568033 小时前
第11章:OpenJDK反射、动态代理与 MethodHandle 初探
java·jvm
晚安日记wanna3 小时前
一条 SMEMBERS 干瘫 Redis 节点:单线程的真正边界在哪
redis·后端·面试
码事漫谈3 小时前
32 位事务号的宿命:金仓 V9 如何用 64 位 XID 破解 PG 三十年顽疾
后端
码事漫谈3 小时前
在 Kubernetes 上管好数据库:金仓 KES-Operator 正式落地
前端·后端
小蒜学长3 小时前
基于SpringBoot+Vue的游戏论坛系统的设计与实现(代码+数据库+LW)
java·后端·springboot·游戏论坛系统·社区生态
SimonKing3 小时前
文档杂乱怎么查找:用 Papra 搭一个极简文档管理系统
java·后端·程序员
captain3763 小时前
网络原理(7)-NAT(Network Address Translation)
java·网络·网络协议·java-ee
掘金者阿豪3 小时前
金仓、MySQL、PostgreSQL 用什么管理工具?DBeaver、Navicat、KStudio 我都试了一遍
后端
九章云极DataCanvas3 小时前
让大模型少做重复计算 九章云极开源分布式KV Cache系统DingoCache
人工智能·开源·token·九章智算云
jaysee-sjc3 小时前
【苍穹外卖】Day01:从零认识企业级项目开发
java·开发语言·数据库·mysql·spring·intellij-idea·mybatis