saga
saga

Reputation: 2113

Asynchronous exceptions in jvm

This paragraph is from the jvm specs:

A Java Virtual Machine may permit a small but bounded amount of execution to occur before an asynchronous exception is thrown. This delay is permitted to allow optimized code to detect and throw these exceptions at points where it is practical to handle them while obeying the semantics of the Java programming language.

I'm having trouble understanding the second part, ie the reason jvm lets the thread run for some time before stopping it.

Upvotes: 2

Views: 85

Answers (1)

Holger
Holger

Reputation: 298123

Let’s recall the definition of asynchronous exceptions:

Most exceptions occur synchronously as a result of an action by the thread in which they occur. An asynchronous exception, by contrast, can potentially occur at any point in the execution of a program.

So when an exception occurs as a result of an action, you simply know that, e.g. when executing an athrow instruction an exception will occur unconditionally, when executing an integer division, the divisor may be zero, or when accessing an object member, the reference may be null. This is a limited set of actions and the optimizer tries its best to reduce it further, using code analysis to prove that the divisor can not be zero, resp. the reference can not be null at specific code locations. Otherwise, it must insert a check for the erroneous condition to generate and handle an exception if necessary. But only at these specific code locations.

In contrast, the asynchronous exception can occur at every code location and may require an explicit check of the “did another thread call stop on my thread since the last check” kind. You don’t want such checks to be performed after every instruction, as that would imply spending more time on such checks than on the actual work.

Hence, it is allowed to perform more than one instruction until the next check, as long as it is guaranteed that the time to reach the next check will be bounded, so this will rule out backward branches with an unpredictable number of iterations without a check. Also keep in mind that in optimized code, there might be uncommitted actions, e.g. the values of modified variables are held in CPU registers. So even after detecting that an asynchronous exception occurred, the code must commit these pending actions, e.g. write back these values to the shared memory, before leaving the code to respond to the exception.

Upvotes: 1

Related Questions