1

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?

Community
  • 1
  • 1
user705414
  • 20,472
  • 39
  • 112
  • 155

6 Answers6

8

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.

Paul
  • 19,704
  • 14
  • 78
  • 96
2
  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.
Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
  • 1
    +1 - The first part of the question is nonsensical. OP - please review the definition of "thread safe". – Stephen C Dec 06 '11 at 00:43
1

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. :|

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
0

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

You can find some code examples here.

adamjmarkham
  • 2,150
  • 2
  • 18
  • 26
0

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();
}
Nate W.
  • 9,141
  • 6
  • 43
  • 65
ratchet freak
  • 47,288
  • 5
  • 68
  • 106