Is synchronized keyword exception-safe?

3.5k Views Asked by At

Possible Duplicate:
Side effects of throwing an exception inside a synchronized clause?

I am wondering if synchronized is exception-safe? Say, an uncaught exception happens within the synchronized block, will the lock be released?

6

There are 6 best solutions below

1
On

Yes, it will. The major point of the synchronize keyword is to make multi-threaded coding easier.

1
On
  1. Synchronize is neither thread-safe nor non-thread-safe. The way you phrased the question just doesn't make sense.
  2. In case of an exception the lock will be released.
0
On

When in doubt, check the Java Language Specification. In section 17.1 you'll find:

If execution of the method's body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor.

0
On

Yes the object will become unlocked if an exception is thrown and not caught.

You can find some code examples here.

0
On

Yes it will.

As a side note, the try-finally construct will ensure the finally block will be executed when the try exits

try {
    someFunctionThatMayThrow();
} finally {
    willAlwaysBeExecuted();
}
0
On

Only a System.exit prevents a block exiting normally. It means finally blocks are not called and locks are not released.

private static final Object lock = new Object();

public static void main(String... args) throws ParseException {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Locking");
            synchronized (lock) {
                System.out.println("Locked");
            }
        }
    }));
    synchronized (lock) {
        System.exit(0);
    }
}

prints

Locking

and hangs. :|