This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Hello everyone, I’m Ah Q!

Above, we have summarized the inevitable execution problems of Finally in the code. In this paper, we will start from the problems encountered in brother B’s interview to analyze the efficiency of a wave of TCF!

Efficiency of TCF

Speaking of TCF efficiency, we have to introduce the exception table, take the above program for example, after decomcompiling the class file, the exception table information is as follows:

  • From: represents the starting position of the range monitored by the exception handler;
  • To: represents the end position of the range monitored by the exception handler (this line is not included in the monitoring range and is the pre-closed and post-open range);
  • Target: indicates the starting position 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:

  1. When an exception is triggered,JVMAll entries in the exception table are traversed from top to bottom;
  2. Compares whether the number of rows that trigger an exception is infromtoWithin the scope;
  3. After a range match, comparisons continue between the types of exceptions thrown and those caught by the exception handlertypeWhether the same;
  4. If the type is the same, jump totargetThe number of rows pointed to starts executing;
  5. If the type is different, the corresponding to the current method will be displayedjavaStack frame, and repeat the operation to the caller;
  6. Worst-case scenarioJVMThe thread needs to be traversedJavaException table for all methods on the stack;

Take the first action: If the command between lines 2 and 4 (the code in the try block) throws an Exception of type Class Java /lang/Exception, skip to line 8 and start executing.

8: ASTORE_1 means to save the thrown exception object to position 1 in the local variable table

From the point of view of bytecode instructions, TCF execution time is negligible if no exceptions are thrown in the code; If item 6 above occurs during code execution, as the exception table is traversed, more exception instances are built and the stack traces required for the exception are generated. This accesses the stack frames of the current thread one by one, recording various debugging information, including the class name, method name, line of code that raised the exception, and so on. So the execution efficiency will be greatly reduced.

See here, do you have a deeper understanding of TCF? Next time I ask you to interview an online interviewer, will you split it 50/50?

Post off

Ah Q will continue to update the Java practice of the article, interested in the public account can pay attention to: AH Q said the code, also can come to the technical group to discuss the problem!