The following is transferred from http://ifeve.com/reentrance-lockout/:
Re-entry locking is very similar to deadlock and nested lock deadlock. Lock and read-write lock both articles involve re-entry locking.
When a thread acquires a lock, a read-write lock, or another non-reentrant synchronizer, a re-entry lock can occur. Reentrant means that a thread can repeatedly acquire a lock that it already holds. Java's synchronized blocks are reentrant. So the following code is not a problem:
(Translator Note: The locks mentioned here refer to the non-reentrant lock implementations, not the lock and Readwritelock classes in the Java class Library)
Public class reentrant{ publicsynchronized outer () { inner (); } Public synchronized inner () { //dosomething }}
Note that both outer () and inner () are declared as synchronized, which in Java is equivalent to the synchronized (this) block (Translator Note: Here are two methods that are instance methods, and synchronized instance methods are equivalent to locking on this. If this is the static method, then read more: Which object is the lock? )。 If a thread calls outer (), the inner () call in outer () is not a problem because two methods are synchronized on the same pipe object (that is, this). If a thread holds a lock on a pipe object, it has access to all the blocks that are synchronized on that pipe object. This is called re-entry. If a thread already holds a lock, it can repeatedly access all blocks of code that use that lock.
The following implementation of this lock is non-reentrant:
Public classlock{Private BooleanisLocked =false; Public synchronized voidLock ()throwsinterruptedexception{ while(isLocked) {wait (); } isLocked=true; } Public synchronized voidunlock () {isLocked=false; Notify (); }}
If a thread does not call the Unlock () method between two calls to lock (), then the second call to lock () is blocked, and a re-entry deadlock occurs.
To avoid re-entry locking there are two options:
- Avoid acquiring locks that are already held once you write code
- Use a reentrant lock
As to which choice is best for your project, it depends on the situation. Reentrant locks are generally not as good as non-reentrant locks and are complex to implement, but these situations may not be a problem in your project. Whether your project is easy to use with locks or locks, reentrant features need to be analyzed specifically for specific problems.
23. Java Concurrency and multithreading-re-entry lock dead