当前位置:网站首页>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 .
边栏推荐
- Runtimeerror in yolox: dataloader worker (PID (s) 17724, 1364, 18928) exited unexpectedly
- String不同创建方式的区别
- 【C语言】详解线程回收函数 pthread_join
- 女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了
- Ask a simple question about SQL
- LabVIEW显示Unicode字符
- Cucumber test practice
- Anaconda's own Spyder editor starts with an error
- ECS 4 sync point, write group, version number
- [C language] explain the thread recycling function pthread_ join
猜你喜欢

c语言 --- 分支结构

要不是和阿里P7聊过,我也不知道自己是个棒槌

Establishment of small and medium-sized enterprise network

HCIE-Security Day41:理论学习:信息收集与网络探测
![[fpga+sin] FPGA implementation of sinusoidal signal generator module based on DDS (direct digital synthesis)](/img/7d/d507d435fe97de005e20560fd6ba35.png)
[fpga+sin] FPGA implementation of sinusoidal signal generator module based on DDS (direct digital synthesis)

I came from a major, so I didn't want to outsource

不使用union实现Mysql 列转行

JVM_ 16_ Garbage collector

【FPGA+sin】基于DDS(直接数字合成)的正弦信号发生器模块FPGA实现

Why is the test post a giant pit? The 8-year-old tester told you not to be fooled
随机推荐
[C language] explain the thread recycling function pthread_ join
Airflow 2.2.3 containerized installation
If you choose the right school, you can enter Huawei as a junior college. I wish I had known
科班出身,结果外包都不要
Nuxt - 每个页面单独设置 SEO 相关标签及网页标题、图标等(页面配置 head)
mysql动态加表只能加小表,加大表跑着跑着任务就不读数据了,有什么解决办法吗
1015 theory of virtue and talent
Redis cache penetration, cache breakdown, cache avalanche
Why is the test post a giant pit? The 8-year-old tester told you not to be fooled
Has my future been considered in the cloud native development route?
【C语言】详解线程回收函数 pthread_join
ECS 4 sync point, write group, version number
moudo网络库剖析
【新功能】Ambire 钱包集成了 Metis 网络
[WC2021] 斐波那契——数论、斐波那契数列
Lua protobuff Emmy Lua wheel
Emotional changes need to be controlled
IDEA修改jvm内存
【FPGA+sin】基于DDS(直接数字合成)的正弦信号发生器模块FPGA实现
Seattention channel attention mechanism