AQS subclass used in each case in synchronization tools

AQS

AQS (AbstractQueuedSynchronizer) is  java.util.concurrent basis. Good encapsulation in synchronization tools JUC propaganda Semaphore , a CountDownLatch , of ReentrantLock , ReentrantReadWriteLock with , a FutureTask, etc., although each has different characteristics, but simple look at the source, within each class contains one of the following internal class definitions:

abstract static class Sync extends AbstractQueuedSynchronizer

At the same time within each class contains such a property, even property names are the same! Comment has hinted, the synchronization mechanism is through this class subclasses of AQS done. Had to sigh: " every powerful synchronization tools, has a heart the same lock! "

/** All mechanics via AbstractQueuedSynchronizer subclass */

private final Sync sync;

Several class provides synchronization functions are actually commissioned sync to complete. Some are part of the function, while others are fully functional.

AQS class in three important attributes:

private transient volatile AbstractQueuedSynchronizer.Node head;
private transient volatile AbstractQueuedSynchronizer.Node tail;
private volatile int state;

Node types are head and tail of a FIFO of the wait Queue ; a type of int Status bits State . AQS here would have guessed that the external presentation (or statement) mainly by the behavior is a status bit and an orderly queue to match complete. The easiest to read of the four main methods:

// acquire an exclusive lock 
public  Final  void Acquire ( int Arg) {

     if (!tryAcquire(arg) &&

        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))

         selfInterrupt();

 }

// release the exclusive lock 
public  Final  boolean Release ( int Arg) {

 if (tryRelease(arg)) {

  Node h = head;

 if (h != null && h.waitStatus != 0)

 unparkSuccessor(h);

 return true;

 }

return false;

 }

// acquire shared locks 
public  Final  void acquireShared ( int Arg) {

       if (tryAcquireShared(arg) < 0)

           doAcquireShared(arg);

}

// release the shared lock 
public  Final  boolean releaseShared ( int Arg) {

        if (tryReleaseShared(arg)) {

            doReleaseShared();

            return true;

        }

        return false;

}

ReentrantLock

ReentrantLock outside the main method is to lock (), tryLock () and unlock () method, of course, there are other variants of lockInterruptibly (), tryLock (long timeout, TimeUnit unit) and so on.

 

lock () function method is to obtain a lock. If you do not use thread returns immediately, and set state to 1 ; if the current thread already has a lock, the state plus 1 ; if another thread owns the lock, then the current thread is not available, wait .

public void lock() {
    sync.lock();
}

tryLock () function is: if the lock is available, then acquire the lock, and returns the value true immediately. If the lock is not available, an immediate return value of false.

public boolean tryLock() {
      return sync.nonfairTryAcquire(1);
  }

unlock () function is to try to release the lock if the current thread owns the lock count minus one, if the count is 0 release the lock. If the thread is not the possession of the current thread, then throw an exception.

public void unlock() {
    sync.release(1);
}

See also aid Sync is done, we look at how the following detailed Sync is to achieve these requirements "rule" of. ReentrantLock constructor tells us that it supports two kinds of equity and non-equity locking mechanism.

public ReentrantLock(boolean fair) {
    sync = (fair)? new FairSync() : new NonfairSync();
}    

In such set corresponding to two kinds of two FairSync and NonfairSync synchronizers, are successor AQS. We can see the corresponding do is lock, release, and Sync the nonfairTryAcquire. AQS source release from the foregoing method is defined in the parent class of AQS, Sync Lock and nonfairTryAcquire are in this particular method, not the parent class coverage of the corresponding method.

lock methods for FairSync and NoFairSync There are two different implementations for unfair lock as long as there is no thread currently holds the lock, the lock will give the current thread; and fair locks can not do, always call acquire methods and, like other threads fair attempt to acquire the lock.

Fairer lock mechanism and the lock mechanism is unfair difference only that if no thread holds the lock, the lock is to assign priority to the current thread (unfair lock), or queue priority assigned to the squadron's first thread (fair lock).

ReentrantLock Summary: 

ReentrantLock defined synchronizer into fair and unfair synchronizer synchronizer. The synchronizer state status bit indicates the current thread holds the lock number reentrant . When acquiring the lock, by covering the AQS tryAcquire (int arg) method, if there is no thread that holds the lock immediately returned, and set state to 1; if the current thread already has a lock, the state plus 1; if another thread owns the lock, the current thread is not available. When the lock is released to cover the AQS tryRelease (int arg), in which method the main role is state status bit reduced release number, expressed releases the lock state if a later is 0, indicates the current thread releases the lock, if not zero It indicates the current thread holds the lock to reduce the number of re-entry.

Since there is a request counter and its possession of a thread , i.e. ReentrantLock achieved reentrant lock .

 

Summary control

This paper focuses on the use of various subclasses of AQS synchronization tool in class, in fact, covering the major synchronization logic of these tools, but the goal is not these few synchronization tools detailed analysis of the code. In addition AQS few final method itself, is the common basis synchronizer, nor is the subject of this paper, it is not expanded in detail. In fact, I am writing this article an initial purpose really just want to list the following table, comparing each sub-category under AQS is how the use of state, actually long-winded so much.

Tools Tools role Tools lock method Tools release lock method Sync method of covering Sync important way of non-coverage state role Lock Type Lock Maintenance
Semaphore Control access to a particular resource while the number of operations acquire:每次请求一个许可都会导致计数器减少1,,一旦达到了0,新的许可请求线程将被挂起 release:每调用 添加一个许可,释放一个正在阻塞的获取者 tryAcquireShared tryReleaseShared   表示初始化的许可数 共享锁 每一次请求acquire()一个许可都会导致计数器减少1,同样每次释放一个许可release()都会导致计数器增加1,一旦达到了0,新的许可请求线程将被挂起。
CountDownLatch 把一组线程全部关在外面,在某个状态时候放开。一种同步机制来保证一个或多个线程等待其他线程完成。 await:在计数器不为0时候阻塞调用线程,为0时候立即返回 countDown :计数递减 tryAcquireShared tryReleaseShared   维护一个计数器 共享锁 初始化一个计数,每次调用countDown方法计数递减,在计数递减到0之前,调用await的线程都会阻塞
ReentrantLock 标准的互斥操作,也就是一次只能有一个线程持有锁 lock:如果没有线程使用则立即返回,并设置state为1;如果当前线程已经占有锁,则state加1;如果其他线程占有锁,则当前线程不可用,等待 tryLock:如果锁可用,则获取锁,并立即返回值 true。如果锁不可用,则此方法将立即返回值 false unlock:尝试释放锁,如果当前线程占有锁则count减一,如果count为0则释放锁。如果占有线程不是当前线程,则抛异常 tryAcquire tryRelease nonfairTryAcquir state表示获得锁的线程对锁的重入次数。 排他锁。 获取锁时,如果没有线程使用则立即返回,并设置state为1;如果当前线程已经占有锁,则state加1;如果其他线程占有锁,则当前线程不可用。释放锁时,在该方法中主要作用是state状态位减少release个,表示释放锁,如果更新后的state为0,表示当前线程释放锁,如果不为0,表示持有锁的当前线程重入数减少
ReentrantReadWriteLock Read-write locks. It allows multiple threads to read while holding the lock, but only one write thread can hold the lock. After the write thread can acquire the write lock acquire the read lock again, but after reading threads acquire the read lock but can not acquire the write lock ReadLock # lock: get a read lock ReadLock # tryLock: try that no other thread currently holds a write lock acquire a read lock WriteLock # lock: obtain a write lock WriteLock # tryLock: When you try to write that no other thread holds the lock, write breath lock. ReadLock # unlock: release the read lock WriteLock # unlock: write lock release acquireShared releaseShared tryAcquire tryRelease tryReadLock tryWriteLock 16 represents a high number of shared locks, the lower 16 bits represent the number of exclusive lock reentry Read lock: shared write locks: exclusive For shared locks, state concept counter. A shared lock on a counter operation with respect to a time equivalent to acquire a shared lock counter is incremented, the release is equivalent to a shared lock counter is decremented by 1; exclusive lock maintenance similar reentrant lock.
FutureTask A package to perform the task to other threads to execute, after the start of execution may be canceled, you can view the results, if the results are not complete obstruction. V get() run() set(V) cancel(boolean) tryAcquireShared tryReleaseShared innerGet innerRun () innerSet innerIsCancelled state status bits to store the execution state RUNNING, RUN, CANCELLED Shared lock Get the results from the thread (there can be multiple) blocks until the thread execution task is completed, or to perform the task was canceled.

 

reference:

http://ifeve.com/abstractqueuedsynchronizer-use/#more-18899

Guess you like

Origin www.cnblogs.com/theRhyme/p/9133901.html