Question

Looking at the Java Virtual Machine Specification and compiled code tells us how "synchronized" blocks are implemented in java. The following code:

public void testSync()
{
    Object obj = getSomeObject();
    synchronized (obj) { doSomething(); }
}

...is roughly equivalent to this pseudocode:

public void testSync()
{
    Object obj = getSomeObject();
    Object __temp = obj;
    monitorenter __temp;
    try { doSomething(); }
    finally { monitorexit __temp; }
}

...with one exception.

For some reason, the exception table displays two finally handlers. For example:

  Exception table:
     from    to  target type
        12    20    23   any
        23    25    23   any

The first handler is where I expect it to be, but the second handler is actually for the finally block of the first handler, and if it catches an exception it executes the same handler. You could visualize this poorly in the following way:

try { doSomething(); }
finally { beginTry: try { monitorexit __temp; } finally { goto beginTry; } }

Does anybody know why this is? If it were just the finally block, the second entry in the table would not be there. Besides, I can't see any possible reason for wanting to execute the finally block again if it's already thrown an exception.

Thanks, Brandon

Was it helpful?

Solution

If it's a choice between trying over and over to release the monitor unsuccessfully, and proceeding without releasing it, both alternatives will cause a deadlock; just if you proceed without releasing then the deadlock doesn't happen until the next time something tries to acquire the monitor, and that problem may be far away from the initial failure. Also trying to release the monitor may work out eventually, while letting the monitor go unreleased is a certain disaster. So you're better off retrying.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top