Reputation: 611
Given the following example:
this example is from "Java Concurrency in Practice".
there is a comment:
Because the doSomething methods in Widget and LoggingWidget are both synchronized, each tries to acquire the lock on the Widget before proceeding.
Why does the method doSomething
in LoggingWidget class need to acquire the lock on the Widget
? If it does, the synchronized
on the method doSomething
in LoggingWidget
is useless, right?
Upvotes: 3
Views: 591
Reputation: 1074
Re-entrant lock will avoid duplicate by re acquiring lock on the object which already has been locked. Now, important thing is releasing lock will not release all the locks. JVM internally maintains counter which will be incremented each time lock is acquired on the object and decremented each time lock will be released. Thus, this mechanism not only avoid dead-lock but also maintains the correctness by keeping count.
Upvotes: 0
Reputation: 328923
Why does the method doSomething in LoggingWidget class need to acquire the lock on the Widget?
Assuming that you want to make sure that 2 threads can't run LoggingWidget#doSomething()
concurrently (in this example, you may want to make sure that the object is not modified between the print statement and the call to super.doSomething()
), then you need to make the method synchronized.
If you don't, a thread (T1) could start running LoggingWidget#doSomething()
and print the object, another thread (T2) could then start running LoggingWidget#doSomething()
too (the method is not synchronized) and print the object again, then T2 could run super.doSomething()
which (let's say) changes the object, and then T1 would execute super.doSomething()
but the state of the object would be different from what it printed because T2 has made changes in the meantime.
One way of preventing that is to make the method synchronized.
Because the doSomething methods in Widget and LoggingWidget are both synchronized, each tries to acquire the lock on the Widget before proceeding.
Reentrant means that a given thread can re-acquire a lock that it already holds. In this case, when a thread enters LoggingWidget#doSomething()
, it acquires this
because the method is synchronized. When it runs super.doSomething()
, it needs to re-acquire the same lock. It intrinsic locks were not reentrant, the thread would block there forever, trying to acquire a lock that it already holds and that it will not release = deadlock.
Upvotes: 2