当前位置:网站首页>Is the interviewer too difficult to serve? A try catch asks so many tricks
Is the interviewer too difficult to serve? A try catch asks so many tricks
2022-06-29 04:17:00 【Ah Q said code】
Hello, everyone , I am Q!
Just got back from the interview B Brother make complaints about it again. : Now the interviewer is too difficult to serve , Put it in a good pile 、 Stack 、 Method area does not ask , Let me analyze it from the perspective of bytecode try-catch-finally( hereinafter referred to as TCF) Efficiency of execution ......
I think it should be that the interviewer looks at the same eight part essay that everyone recites during the interview , I don't think it's necessary to ask , Then he turned the corner to test everyone's understanding . Today while B Brother is there, too , Let's sum up TCF Related knowledge , Look forward to meeting the interviewer next time !
Environmental preparation :IntelliJ IDEA 2020.2.3、JDK 1.8.0_181
Execution order
Let's write a simple code first :
public static int test1() {
int x = 1;
try {
return x;
} finally {
x = 2;
}
}
The answer is 1 No 2, Are you right ?
We all know that TCF in , Execute to return I'll do it first finally The operation , Then it will return to execute return, Then why is it here 1 Well ? Let's decompile the bytecode file .
command :javap -v xxx.class
Bytecode instructions are obscure , Let's explain it graphically ( Let's just look at the front 7 Line instruction ): First, execute int x = 1;
Then we need to implement try Medium return x;
This is not a real return x Value , It's going to be x The value of is stored in the local variable table as Temporary storage variables For storage , That is, the value is Protect operation .
The last to enter finally In the implementation of x=2;
At this time, though x Has been assigned to 2 了 , But due to the protection operation just now , In the execution of real return In operation , Will be protected Temporary storage variables Stack back .
In order to better understand the above operations , Let's write a simple piece of code :
public static int test2() {
int x = 1;
try {
return x;
} finally {
x = 2;
return x;
}
}
Let's think about the implementation results ? The answer is 2 No 1.
Let's look at the bytecode instructions of the program
Through comparison, we found that , The first 6 OK, one is iload_1, One is iload_0, What determines this ? The reason is that we mentioned above protection mechanism , When in finally in return When the sentence is , The protection mechanism will fail , Instead, put the value of the variable on the stack and return .
Summary
returnExecution priority is higher thanfinallyThe execution priority of , howeverreturnThe function does not end immediately after the statement is executed , Instead, save the results to Stack frame Medium Local variable table in , And then go ahead and do itfinallyStatement in block ;- If
finallyThe block containsreturnsentence , It won't be righttryThe value to be returned in the block is protected , But jump straight tofinallyExecute in statement , And finally infinallyStatement returns , The return value is infinallyThe changed value in the block ;
finally Why is it necessary to execute
Careful little friends should be able to find , The above bytecode instruction diagram shows the first 4-7 Xing He 9-12 The bytecode instructions of the lines are exactly the same , So why do the instructions repeat ?
First, let's analyze what these repeated instructions do , After analysis, it is found that they are x = 2;return x; Bytecode instructions for , That is to say finally Code in a code block . Therefore, we have reason to suspect that if the above code is added catch Code block ,finally The bytecode instruction corresponding to the code block will also appear again .
public static int test2() {
int x = 1;
try {
return x;
} catch(Exception e) {
x = 3;
} finally {
x = 2;
return x;
}
}
After decompiling
As we expected , Repeated bytecode instructions appear three times . Let's return to the original question , Why? finally The bytecode instruction of the code will repeat three times ?
Turned out to be JVM In order to ensure the execution process of all abnormal paths and normal paths finally The code in , So in try and catch After that, we added finally Bytecode instructions in , Plus its own instructions , Exactly three times . That's why finally The reason why it must be implemented .
finally Must it be carried out ?
Why has it been said above finally The code in must execute , Now we have to do more ? Please have a look at
Under normal circumstances , It is bound to be executed , But there are at least three situations , It must not be implemented :
tryThe statement returns... Without being executed , suchfinallyStatement will not execute , It also shows thatfinallyThe necessary but not sufficient condition for a statement to be executed is : CorrespondingtryThe statement must be executed until ;tryCode block hasSystem.exit(0);Such a statement , becauseSystem.exit(0);Is terminationJVMOf , evenJVMIt's all stopped ,finallyIt won't be executed ;- The daemon will exit with the exit of all non daemon threads , When The guardian thread Inside
finallyYour code has not been executed to , When a non daemon thread terminates or exits ,finallyIt will not be executed ;
TCF The efficiency of
Speaking of TCF The efficiency of , We have to introduce Anomaly table , Take the program above , Decompile class The exception table information after the file is as follows :
- from: Represents the starting position of the range monitored by the exception handler ;
- to: Represents the end of the range monitored by the exception handler ( This line is not included in the scope of monitoring , It's the front closed and back open section );
- target: Point to the start of the exception handler ;
- type: Represents the type of exception caught by the exception handler ;
Each line in the figure represents an exception handler
Workflow :
- When an exception is triggered ,
JVMAll entries in the exception table will be traversed from top to bottom ; - Compare whether the number of rows triggering the exception is in
from-toWithin the scope of ; - After range matching , It will continue to compare the exception types thrown with the exception types caught by the exception handler
typeAre they the same? ; - If the type is the same , Will jump to
targetThe number of rows pointed to starts execution ; - If the type is different , The current method corresponding to... Will pop up
javaStack frame , And repeat the operation for the caller ; - At worst
JVMYou need to traverse the threadJavaException table for all methods on the stack ;
Take the first behavior : If located 2-4 Commands between lines ( namely try Code in block ) Throw out Class java/lang/Exception Exception of type , Then jump to 8 Line start execution .
8: astore_1It refers to the method of saving the thrown exception object to the local variable table 1 Location
From the perspective of bytecode instructions , If there is no exception thrown in the code ,TCF The execution time is negligible ; If the code execution process occurs in the above section 6 strip , Then, with the traversal of the exception table , More exception instances are built , The stack trace required by the exception is also being generated . This operation accesses the stack frame of the current thread one by one , Record various debugging information , Including the name of the class 、 Method name 、 The number of lines of code that triggered the exception, and so on . Therefore, the execution efficiency will be greatly reduced .
边栏推荐
- MySQL can only add small tables when adding tables dynamically. If you increase the size of tables, you won't read data when running tasks. Is there any solution
- 大神们 在富函数的open中从mysql连接池里取连接 连接池初始化是20个 如果富函数的并行度是1
- 热更新流程
- How to keep database and cache consistent
- 科班出身,结果外包都不要
- Libuv library overview and comparison of libevent, libev and libuv (Reprint)
- Idea modifying JVM memory
- On June 27, 2022, I have the right to choose the journey of the summer vacation.
- c语言 --- 分支结构
- PostgreSQL 出现cross-database references are not implemented的bug
猜你喜欢

Analysis of moudo Network Library

SqlServer如何查询除去整列字段为null的结果

【C语言】 详解线程退出函数 pthread_exit

How sqlserver queries and removes results with null fields in the whole column

MySQL复习资料(附加)case when

New listing of operation light 3.0 -- a sincere work of self subversion across the times

【C语言】解决 “address of stack memory associated with local variable ‘num‘ returned”

Why is the test post a giant pit? The 8-year-old tester told you not to be fooled
![[new function] ambire wallet integrates Metis network](/img/29/8a8c0cd40c51cef1174ee59706d4c9.png)
[new function] ambire wallet integrates Metis network

要不是和阿里P7聊过,我也不知道自己是个棒槌
随机推荐
[WC2021] 斐波那契——数论、斐波那契数列
选对学校,专科也能进华为~早知道就好了
【FPGA+sin】基于DDS(直接数字合成)的正弦信号发生器模块FPGA实现
人民银行印发《关于支持外贸新业态跨境人民币结算的通知》
Canoe- how to parse messages and display information in the trace window (use of program node and structure type system variables)
Blue Bridge Cup DFS (I)
Libuv library overview and comparison of libevent, libev and libuv (Reprint)
Inftnews | metauniverse technology will bring a new shopping experience
Redis cache penetration, cache breakdown, cache avalanche
【HackTheBox】dancing(SMB)
Does cdc2.2.1 not support postgresql14.1? Based on the pgbouncer connection mode, with 5433
iNFTnews | 元宇宙技术将带来全新的购物体验
Sword finger offer II 040 Largest rectangle in matrix
[C language] explain the thread exit function pthread_ exit
The five levels of making money, which level are you on?
JSX的基本使用
请问大佬,Oracle CDC报错 Call snapshotState on closed sou
Libuv库概述及libevent、libev、libuv对比(转载)
PATH 与 LD_LIBRARY_PATH 的用法举例
JVM_ 16_ Garbage collector