Lock as a tool for concurrent shared data, ensuring consistency, there are many implementations in the Java platform (such as synchronized and Reentrantlock, etc.). These locks have been written to provide convenience for our development, but the specific nature and type of the lock are rarely mentioned. This series of articles will analyze common lock names and features in Java to help you answer questions.
Four, can be re-entry lock:
This article is about a generalized reentrant lock, rather than a single-Reentrantlock under Java.
A reentrant lock, also called a recursive lock, means that the inner recursive function still has the code to acquire the lock after the same thread's outer function acquires the lock, but is unaffected.
Both Reentrantlock and synchronized are reentrant locks in the Java environment.
Here is the usage example:
public class Test implements runnable{public synchronized void get () { System.out.println (Thread.CurrentThread (). GetId ()); Set (); } public synchronized void set () { System.out.println (Thread.CurrentThread (). GetId ())} @Override public void Run () { get ();} public static void Main (string[] args) { Test ss=new test (); New Thread (ss). Start (); New Thread (ss). Start (); New Thread (ss). Start (); }}
Two examples The final result is correct, that is, the same thread ID is continuously output two times.
The results are as follows:
Threadid:8threadid:8threadid:10threadid:10threadid:9threadid:9
the maximum effect of reentrant locks is to avoid deadlocks.
we use spin locks as an example.
public class SpinLock {private atomicreference<thread> owner =new atomicreference<> (), public void Lock () {
thread current = Thread.CurrentThread (); while (!owner.compareandset (null, current)) { }} publicly void Unlock () { Thread current = Thread.CurrentThread (); Owner.compareandset (current, null);}}
For spin locks:
1, if the same thread two call lock (), will cause the second call to the lock position spin, resulting in a deadlock
Indicates that the lock is not reentrant. (Within the lock function, you should verify that the thread is the thread that has acquired the lock)
2, if the 1 problem has been resolved, when unlock () First Call, the lock has been released. You should not actually release the lock.
(statistics are used in counting times)
After the modification, the following:
public class SpinLock1 {private atomicreference<thread> owner =new atomicreference<> (); private int count = 0; public void Lock () { Thread current = Thread.CurrentThread (); if (Current==owner.get ()) { count++; return; } while (!owner.compareandset (null, current)) { }} publicly void Unlock () { Thread current = Thread.CurrentThread (); if (Current==owner.get ()) { if (count!=0) { count--; } else{ Owner.compareandset (current, null);}}}
The spin lock is a re-entry lock.
Introduction to the reentrant locking of Java locks