Lock brief introduction
Let's come down and see concurent Under bag lock subpackage . Locks are used to control the way multiple threads access shared resources , Generally speaking , A lock prevents multiple threads from accessing shared resources at the same time . stay Lock Before the interface appeared ,java The procedure mainly depends on synchronized Keyword to achieve the lock function of , and java SE5 after , And... Is added to the contract lock Interface , It provides with synchronized Same lock function . Although it lost something like synchronize Keyword implicit locking and unlocking convenience , But it has the operability of lock acquisition and release , There are many kinds of interruptible lock acquisition and timeout lock acquisition synchronized Keywords do not have the synchronization features . Display is usually used lock In the form of :
Lock lock = new ReentrantLock(); lock.lock(); try { … } finally
{
lock.unlock(); }
It should be noted that synchronized The lock will be released automatically when the synchronization block is completed or an exception is encountered , and lock Must call unlock() Method release lock , So in finally Release lock in block .
Lock Interface API
Let's take a look at it now lock Which methods are defined by the interface :
// Get the lock
void lock();
// The process of obtaining a lock can respond to an interrupt
void lockInterruptibly() throws InterruptedException;
// Non blocking response interrupts can immediately return , Get lock back true Instead, return to fasle
boolean tryLock();
// Timeout lock acquisition , The lock can be obtained within the timeout or without interruption
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
// To obtain and lock The bound wait notification component , The current thread must acquire a lock to wait , When waiting, the lock will be released first , When the lock is acquired again, it can return from the waiting
Condition newCondition();
// Release the lock .
unlock();
It's on it lock Six methods under the interface , I just translated it from the source code into English , If you are interested, you can go and have a look by yourself . So in locks Which classes under the package implement the interface ? Start with the most familiar ReentrantLock Speaking of .
public class ReentrantLock implements Lock, java.io.Serializable
Select all code copy
Obviously ReentrantLock Realized lock Interface , Next, let's take a closer look at how it is implemented .java Training when you look at the source code, you will be surprised to find ReentrantLock There's not much code , Another obvious feature is : Basically, the implementation of all methods actually calls their static memory classes Sync The method in , and Sync Class inherited AbstractQueuedSynchronizer(AQS). You can see that if you want to understand ReentrantLock The key is to synchronize the queue AbstractQueuedSynchronizer( Referred to as synchronizer ) The understanding of the .
First time to know AQS
About AQS There is a very specific explanation in the source code :
Provides a framework for implementing blocking locks and related
synchronizers (semaphores, events, etc) that rely on
first-in-first-out (FIFO) wait queues. This class is designed to be
a useful basis for most kinds of synchronizers that rely on a single
atomic {@code int} value to represent state. Subclasses must define
the protected methods that change this state, and which define what
that state means in terms of this object being acquired or released.
Given these, the other methods in this class carry out all queuing
and blocking mechanics. Subclasses can maintain other state fields,
but only the atomically updated {@code int} value manipulated using
methods {@link #getState}, {@link #setState} and {@link
compareAndSetState} is tracked with respect to synchronization.
Subclasses should be defined as non-public internal helper classes
that are used to implement the synchronization properties of their
enclosing class. Class {@code AbstractQueuedSynchronizer} does not
implement any synchronization interface. Instead it defines methods
such as {@link #acquireInterruptibly} that can be invoked as
appropriate by concrete locks and related synchronizers to implement
their public methods.
Select all code copy
Synchronizer is the basic framework used to build locks and other synchronization components , Its implementation mainly depends on a int Member variables to represent the synchronization status and through a FIFO Queues form waiting queues . Its subclasses must override AQS Several protected Modified method for changing synchronization state , Other methods mainly implement queuing and blocking mechanisms . Status updates use getState,setState as well as compareAndSetState These three methods .
Subclasses are recommended to be defined as static inner classes of custom synchronization components , Synchronizer itself does not implement any synchronization interface , It just defines a number of synchronization state acquisition and release methods for the use of custom synchronization components , Synchronizer supports exclusive access to synchronization state , It can also support shared access to synchronization state , In this way, it is convenient to implement different types of synchronization components .
Synchronizer is to realize lock ( It can also be any synchronous component ) The key to , Aggregate synchronizers in lock implementation , Using synchronizer to realize the semantics of lock . The relationship between the two can be understood in this way : The lock is user oriented , It defines the interface between the user and the lock , Hidden implementation details ; Synchronizer is a lock oriented implementer , It simplifies the way locks are implemented , Shielding the management of synchronization status , Thread queuing , Wait and wake up and other low-level operations . Locks and synchronizers well isolate the areas that users and implementers need to focus on .
key word :java train
![[Yugong series] February 2022 wechat applet -app Subpackages and preloadrule of JSON configuration attribute](/img/94/a2447b3b00ad0d8fb990917531316d.jpg)







