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?
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?
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.
On
Yes the object will become unlocked if an exception is thrown and not caught.
You can find some code examples here.
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. :|
Yes, it will. The major point of the synchronize keyword is to make multi-threaded coding easier.