当前位置: 首页 > news >正文

揭开JVM所看到的try/catch/finally

为什么80%的码农都做不了架构师?>>>   hot3.png

#揭开JVM所看到的try/catch/finally 最近有一位朋友发了一段代码给我,这个方法很简单,具体内容大致如下:

int num = 5000000;//500万 
long begin = System.currentTimeMillis();
for(int i=0; i<num; i++){
   try{ 
        //do something
      }catch(Exception e){

      }
 }
long end = System.currentTimeMillis();
System.out.println("==============使用时间:" + (end - begin) + " 毫秒");

上面代码可以看到是通过执行该循环体所消耗的时间,通过和把try/cache注释掉进行对比,最后得到的结果时间比较随机,执行的耗时和try/cache没有必然的联系,那try/cache究竟会不会影响代码的执行效率呢?从java语言的源码上看貌似多执行了一些指令,实际上是怎么样的呢?下面我分几个场景来分析一下jvm对try/cache的处理过程。 ##单层的try/catch 下面是一个只有单层的try/catch代码块

 public int test(int a,int b){
        try{
            return a+b;
        }catch (Exception e){
            throw new CustomException();
        }
    }

通过javap -v查看JVM编译成class字节码之后是如何处理这个try/catch

public int test(int, int);
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=4, args_size=3
         0: iload_1                          // 将第一个int参数压入队列(第一个入参)
         1: iload_2                          // 将第二个int参数压入队列(第二个入参)
         2: iadd                             //弹出队列中第一个和第二个参数执行相加,并把相加结果压入队列
         3: ireturn                          //弹出队列第一个元素,并return。
         4: astore_3                         //此处是try开始的逻辑
         5: new           #3                 // class com/bieber/demo/CustomException
         8: dup                                
         9: invokespecial #4                 // Method com/bieber/demo/CustomException."<init>":()V
        12: athrow                           //将队列中的第一个元素弹出,并当做异常抛出,到此整个方法体完毕
     Exception table:
         from    to  target type
             0     3     4   Class java/lang/Exception
     LineNumberTable:
        line 13: 0
        line 14: 4
        line 15: 5
     LocalVariableTable:
        Start  Length  Slot  Name   Signature
               5       8     3     e   Ljava/lang/Exception;
               0      13     0  this   Lcom/cainiao/cilogisticservice/ExceptionClass;
               0      13     1     a   I
               0      13     2     b   I
     StackMapTable: number_of_entries = 1
          frame_type = 68 /* same_locals_1_stack_item */
          stack = [ class java/lang/Exception ]

上面是test方法JVM编译之后的结果,上面的Code块是整个方法体的内容,而从0-3可以视为是方法体的正常逻辑,4-12可以视为try/catch块,从方法体的指令看,正常情况下执行到3的地方就完毕了,而不会去执行4-12的指令。那是不是就得出结论,try/catch代码块在正常逻辑的时候是不会被执行的,于是对于对代码加上try/catch块,并不会影响代码的执行效率,因为根本不会有多余的指令被执行,只有出现异常的时候才会多出执行异常的指令。其实本文到这里基本上可以结束了,因为得到了我想要的答案(try/catch代码块对代码性能的影响)。为了让整个问题能够更加全面一点,下面对JVM如何处理一个try/catch做更加深入的调研。

上面的JVM编译的字节码的时候除了Code代码块,还有Exception table代码块,从这个代码块的内容可以看到,包含四列(from,to,target,type),其中fromto表示这个try/catch代码块是从哪开始到哪结束,可以看到上面的try/catch代码块是从Code代码块的0-3,也就是从加载第一个int值到返回结果的代码块,target表示这个try/catch代码块执行逻辑在哪里开始,比如上面的表示从Code中的4开始,也就是astore_3指令开始,直到athrow指令被执行的地方,在Exception table中的一行还有type列,表示是这个异常类型,用于在一个try/catch代码块出现多个catch内容,用于匹配正确的异常类型。下面我列出这种情况:

##一个try对应多个catch 我将上面的代码调整成了下面结构:

 public int test(int a,int b){
        try{
            return a+b;
        }catch (Exception e){
            a++;
            throw new CustomException();
        }catch (Throwable t){
            b++;
            throw new CustomException();
        }
    }

JVM对上面代码编译后的结果:

 public int test(int, int);
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=4, args_size=3
         0: iload_1       
         1: iload_2       
         2: iadd          
         3: ireturn       
         4: astore_3      
         5: iinc          1, 1
         8: new           #3                  // class com/bieber/demo/CustomException
        11: dup           
        12: invokespecial #4                  // Method com/bieber/demo/CustomException."<init>":()V
        15: athrow        
        16: astore_3      
        17: iinc          2, 1
        20: new           #3                  // class com/cainiao/cilogisticservice/CustomException
        23: dup           
        24: invokespecial #4                  // Method com/cainiao/cilogisticservice/CustomException."<init>":()V
        27: athrow        
      Exception table:
         from    to  target type
             0     3     4   Class java/lang/Exception
             0     3    16   Class java/lang/Throwable
      LineNumberTable:
        line 13: 0
        line 14: 4
        line 15: 5
        line 16: 8
        line 17: 16
        line 18: 17
        line 19: 20
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               5      11     3     e   Ljava/lang/Exception;
              17      11     3     t   Ljava/lang/Throwable;
               0      28     0  this   Lcom/cainiao/cilogisticservice/ExceptionClass;
               0      28     1     a   I
               0      28     2     b   I
      StackMapTable: number_of_entries = 2
           frame_type = 68 /* same_locals_1_stack_item */
          stack = [ class java/lang/Exception ]
           frame_type = 75 /* same_locals_1_stack_item */
          stack = [ class java/lang/Throwable ]

和上面的内容对比一下会发现,在Code中多出了一段astore_3/athrow块,并且在Exception table中多了一行,想想通过上面的解释,对这个多出的一行的目的应该都知道是用来什么的,由于我在catch中成了throw之外,还多了一个++的操作,可以看到在astore_3/athrow块中多出了iinc指令,所以可以理解,try/catch在JVM中对应的是一个子代码块,在条件满足(出现匹配的catch异常)的时候会被执行。

下面我整理一下当出现异常的(这里说的是有try/catch的异常)JVM处理流程:

1、在try/catch出现异常
2、JVM会去`Exception table`查找匹配的异常类型
3、假设匹配上了,那么读取from,to,target,获取待执行的`try/catch`块的指令(具体是否抛出,看是否有athrow指令)。

为了更加了解JVM对try的处理,下面对try/finally再调研一下。

##try/finally块的执行处理

调整代码逻辑,如下:

public int test(int a,int b){
        try{
            return a+b;
        }catch (Exception e){
            a++;
            throw new CustomException();
        }finally {
            b++;
        }
    }

JVM编译后的指令:

  public int test(int, int);
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=5, args_size=3
         0: iload_1       
         1: iload_2       
         2: iadd          
         3: istore_3                         //将栈顶的元素存储局部变量数组的第三个位置
         4: iinc          2, 1               //执行b++
         7: iload_3                          //把局部变量第三个位置的数值压入栈顶
         8: ireturn                          //弹出栈顶,并且返回
         9: astore_3      
        10: iinc          1, 1               //a++
        13: new           #3                  // class com/bieber/demo/CustomException
        16: dup           
        17: invokespecial #4                  // Method com/bieber/demo/CustomException."<init>":()V
        20: athrow        
        21: astore        4
        23: iinc          2, 1                //b++
        26: aload         4
        28: athrow        
      Exception table:
         from    to  target type
             0     4     9   Class java/lang/Exception
             0     4    21   any
             9    23    21   any
      LineNumberTable:
        line 13: 0
        line 18: 4
        line 14: 9
        line 15: 10
        line 16: 13
        line 18: 21
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
              10      11     3     e   Ljava/lang/Exception;
               0      29     0  this   Lcom/cainiao/cilogisticservice/ExceptionClass;
               0      29     1     a   I
               0      29     2     b   I
      StackMapTable: number_of_entries = 2
           frame_type = 73 /* same_locals_1_stack_item */
          stack = [ class java/lang/Exception ]
           frame_type = 75 /* same_locals_1_stack_item */
          stack = [ class java/lang/Throwable ]

通过上面的代码,你会发现在Exception table都出了两行,其实我们只是在代码中只有一个try/catch块,而这里出现了三个,那么另外两个是做什么的呢?可以看到多出的两行的type都是any,这里的any表示的是任何异常类型,多出的第一行,是从0-4,表示0-4之间的指令出现异常,会从21的指令开始执行,发现执行的是b++(finally)的内容,多出的第二行是9-23,表示9-23之间的指令被执行的过程中出现异常也会从21行开始执行(也是执行finally的内容),而9-23其实是catch的代码逻辑。上面均是出现了异常会触发finally的代码执行,正常情况下会发现4的位置执行了finally的内容,然后再执行ireturn指令,这里可以得出,JVM处理finally其实是对于正常的指令队列增加了finally代码块的指令,以及对异常中添加了finally代码块的指令,这也就导致了fianlly在任何地方都可以被执行,其实就是冗余了指令队列(其实思想比较简单)。

到此,对JVM如何处理try/catch/finally块进行了简单的介绍,目的是让大家对添加try代码块不要吝啬,在需要的时候,还是需要做一些异常的控制,让代码的异常逻辑更加完善,而不是一直将异常抛给外面处理,因为外面可能并不知道你这个异常是什么意思。

转载于:https://my.oschina.net/bieber/blog/703251

相关文章:

  • debian useful packages
  • 图形绘制-线段绘制相关
  • wget 命令用法详解
  • 介绍一个基于jQuery的Cookie操作插件
  • 并查集的应用
  • 37条常用Linux Shell命令组合
  • 运维小技巧:使用ss命令代替 netstat,和netstat说再见
  • 弹出框插件——dialog
  • 小强的HTML5移动开发之路(21)—— PhoneGap
  • dba基础课程-linux操作系统:系统信息命令
  • 定位被选中的select
  • 创新团队中常见的几种“怪人”
  • div/iframe自适应浏览器宽度高度问题
  • Linux下PHP支持oracle,安装oracle instant client,pdo_oci笔记
  • EBS JSP文件编译命令
  • 【node学习】协程
  • Angular6错误 Service: No provider for Renderer2
  • const let
  • iBatis和MyBatis在使用ResultMap对应关系时的区别
  • javascript 哈希表
  • Kibana配置logstash,报表一体化
  • mysql innodb 索引使用指南
  • oldjun 检测网站的经验
  • php面试题 汇集2
  • Python爬虫--- 1.3 BS4库的解析器
  • python学习笔记-类对象的信息
  • scrapy学习之路4(itemloder的使用)
  • 阿里中间件开源组件:Sentinel 0.2.0正式发布
  • 个人博客开发系列:评论功能之GitHub账号OAuth授权
  • 今年的LC3大会没了?
  • 温故知新之javascript面向对象
  • 我建了一个叫Hello World的项目
  • 在 Chrome DevTools 中调试 JavaScript 入门
  • 阿里云ACE认证之理解CDN技术
  • #define 用法
  • $$$$GB2312-80区位编码表$$$$
  • (2020)Java后端开发----(面试题和笔试题)
  • (C语言)求出1,2,5三个数不同个数组合为100的组合个数
  • (echarts)echarts使用时重新加载数据之前的数据存留在图上的问题
  • (LeetCode 49)Anagrams
  • (ZT)出版业改革:该死的死,该生的生
  • (二)学习JVM —— 垃圾回收机制
  • (附源码)ssm高校升本考试管理系统 毕业设计 201631
  • (求助)用傲游上csdn博客时标签栏和网址栏一直显示袁萌 的头像
  • (一)使用IDEA创建Maven项目和Maven使用入门(配图详解)
  • (转) ns2/nam与nam实现相关的文件
  • (转)利用PHP的debug_backtrace函数,实现PHP文件权限管理、动态加载 【反射】...
  • .cn根服务器被攻击之后
  • .gitignore文件—git忽略文件
  • .NET/C# 使用 SpanT 为字符串处理提升性能
  • .NET开源项目介绍及资源推荐:数据持久层
  • .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验
  • ::before和::after 常见的用法
  • [ IOS ] iOS-控制器View的创建和生命周期
  • [ vulhub漏洞复现篇 ] Jetty WEB-INF 文件读取复现CVE-2021-34429