|
original link Jakob Jenkov Translator: Liu Xiaozhi proofreading: Ding
Re-entry locking is very similar to deadlock in Java. 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{
- Public synchronized outer () {
- Inner ();
- }
- Public synchronized inner () {
- Do something
- }
- }
Copy Code
Meaning 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, The instance method of synchronized is equivalent to locking on this and, if it is a static method, otherwise, if a thread calls outer (), the inner () call in outer () is not a problem, since two methods are all in the same pipe object ( This is the synchronization. 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 class lock{
- Private Boolean isLocked = false;
- Public synchronized void Lock ()
- Throws interruptedexception{
- while (isLocked) {
- Wait ();
- }
- IsLocked = true;
- }
- public synchronized void unlock () {
- isLocked = false;
- Notify ();
- }
- }
Copy Code
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.
|