Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Side effects of throwing an exception inside a synchronized clause?

Are there any unclear side effects to throwing an exception from within a synchronized clause? What happens to the lock?

private void doSomething() throws Exception {...}  synchronized (lock) {        doSomething();        } 
like image 846
Yossale Avatar asked Jan 07 '10 09:01

Yossale


People also ask

What happens if exception is thrown in synchronized block?

As mentioned if an exception occurs then it should be handled/thrown to continue the execution or else execution will stop. So, it is same in your scenario if an exception happens then it would be handled and further the lock will be released.

What will happen when an exception occurs from within a synchronized code block will lock be retained or released?

When an exception occurs from within a synchronized code block, then JVM smartly releases all the locks acquired by the current thread and will start unwinding the execution stack, till the exception is handled using catch block, otherwise killing the thread.

What happens after throwing an exception?

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.

Does throwing an exception have to cause program termination?

No, it does not have to cause it to terminate. You could catch the exception and do something useful with it, like show a message to the user that an error occurred and why.


2 Answers

I see no side-effect.

The lock is guaranteed to be terminated in all cases, and an exception is no exception (pun intended).

like image 178
KLE Avatar answered Oct 01 '22 11:10

KLE


As you would hope, the lock is released normally.

For reference, the appropriate section of the JLS which guarantees this behaviour is § 14.19:

If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason.

('abrupt completion' is defined elsewhere in the JLS to include exceptions from JVM, exceptions raised by throw, and use of the break, continue, or return statements to transfer outside the block.)

like image 26
Cowan Avatar answered Oct 01 '22 11:10

Cowan