Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Java thread aquire a lock while already holding it?

If a thread holds a lock , what happens when the thread needs to enter another critical section controlled by the same lock?

like image 721
Saurabh Gokhale Avatar asked Feb 28 '23 03:02

Saurabh Gokhale


2 Answers

Intrinsic locks (synchronized) in Java are reentrant, thus the JVM will recognize that the current thread already holds this lock and it will proceed.

There are also explicit locks, that are reentrant.

If a lock is not reentrant, you could for instance not use recursive methods.

like image 135
b_erb Avatar answered Mar 02 '23 13:03

b_erb


nothing: the system is able to determine which thread holds the lock to avoid a thread blocking itself.

like image 21
Maurice Perry Avatar answered Mar 02 '23 13:03

Maurice Perry