精品亚洲aⅴ在线观看-精品亚洲av高清一区二区三区-精品亚洲av无码喷奶水糖心al-精品亚洲av无码一区-精品亚洲av无码一区二-精品亚洲av无码一区二区

相關欄目
新聞資訊 >>
合作媒體 >>
展會知識 >>
當前位置:首頁 >

真沒想到(AQS原理解析)aqs原理,


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 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 int value manipulated using methods getState, setState and compareAndSetState is tracked with respect to synchronization.

AQS此類旨在成為大多數依賴單個原子 int 值來表示狀態的同步器的有用基礎。

AQS提供了一個框架來實現依賴于FIFO Thread等待隊列的阻塞鎖及其對應的同步器

AQS的子類必須重寫AQS的protected方法(tryAcquire、tryRelease、tryAcquireShared、tryReleaseShared、isHeldExclusively),這些方法可以改變state,定義其對象被獲取和釋放時state的含義。其他的方法執行隊列和阻塞機制,AQS子類可以維護其他狀態字段,但是只有對單個原子 int 值狀態更新的方法(getState, setState and compareAndSetState)會被用于同步

Subclasses should be defined as non-public internal helper classes that are used to implement the synchronization properties of their enclosing class. Class AbstractQueuedSynchronizer does not implement any synchronization interface. Instead it defines methods such as acquireInterruptibly that can be invoked as appropriate by concrete locks and related synchronizers to implement their public methods.

AQS子類應該被定義成non-public的內部幫助類來用于實現其封閉(外部)類的同步屬性。

AQS不實現任何同步器接口,相反,它定義了諸如acquireInterruptively 之類的方法,這些方法可以由具體鎖和相關同步器適當調用以實現它們的公共方法。下面給出AQS的字段,一個“雙端隊列”,一個state,再加上unsafe(提供CAS操作)

public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable { /** * Head of the wait queue, lazily initialized. Except for * initialization, it is modified only via method setHead. Note: * If head exists, its waitStatus is guaranteed not to be * CANCELLED. */ private transient volatile Node head; /** * Tail of the wait queue, lazily initialized. Modified only via * method enq to add new wait node. */ private transient volatile Node tail; /** * The synchronization state. */ private volatile int state; /** * Setup to support compareAndSet. We need to natively implement * this here: For the sake of permitting future enhancements, we * cannot explicitly subclass AtomicInteger, which would be * efficient and useful otherwise. So, as the lesser of evils, we * natively implement using hotspot intrinsics API. And while we * are at it, we do the same for other CASable fields (which could * otherwise be done with atomic field updaters). */ private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long stateOffset; private static final long headOffset; private static final long tailOffset; private static final long waitStatusOffset; private static final long nextOffset; }

AQS繼承了抽象類AbstractOwnableSynchronizer,這個類非常簡單,只有一個變量,那就是owner線程。這個類可能涉及到ownership概念的同步器的基礎

A synchronizer that may be exclusively owned by a thread. This class provides a basis for creating locks and related synchronizers that may entail a notion of ownership. The AbstractOwnableSynchronizer class itself does not manage or use this information. However, subclasses and tools may use appropriately maintained values to help control and monitor access and provide diagnostics.

public abstract class AbstractOwnableSynchronizer implements java.io.Serializable { /** * The current owner of exclusive mode synchronization. */ private transient Thread exclusiveOwnerThread; }

繼續說AQS

This class supports either or both a default exclusive mode and a shared mode. When acquired in exclusive mode, attempted acquires by other threads cannot succeed. Shared mode acquires by multiple threads may (but need not) succeed. This class does not "understand" these differences except in the mechanical sense that when a shared mode acquire succeeds, the next waiting thread (if one exists) must also determine whether it can acquire as well. Threads waiting in the different modes share the same FIFO queue. Usually, implementation subclasses support only one of these modes, but both can come into play for example in a ReadWriteLock. Subclasses that support only exclusive or only shared modes need not define the methods supporting the unused mode.

AQS支持默認獨占模式和共享模式中的一種或兩種。 當以獨占模式獲取時,其他線程嘗試獲取不會成功。 共享模式下多個線程獲取可能(但不一定)成功。 AQS不“理解”這些差異,除了機械意義上的區別,當共享模式獲取成功時,下一個等待線程(如果存在)也必須確定它是否也可以獲取。 在不同模式下等待的線程共享同一個 FIFO 隊列。 通常,實現子類只支持這些模式中的一種,但兩種模式都可以發揮作用,例如在 ReadWriteLock 中。 僅支持獨占或僅共享模式的子類不需要定義支持未使用模式的方法。

This class defines a nested AbstractQueuedSynchronizer.ConditionObject class that can be used as a Condition implementation by subclasses supporting exclusive mode for which method isHeldExclusively reports whether synchronization is exclusively held with respect to the current thread, method release invoked with the current getState value fully releases this object, and acquire, given this saved state value, eventually restores this object to its previous acquired state. No AbstractQueuedSynchronizer method otherwise creates such a condition, so if this constraint cannot be met, do not use it. The behavior of AbstractQueuedSynchronizer.ConditionObject depends of course on the semantics of its synchronizer implementation.

該類定義了一個嵌套的 AbstractQueuedSynchronizer.ConditionObject 類,該類可以被支持獨占模式的子類用作 Condition 實現,其中方法 isHeldExclusively 報告“同步”是否被當前線程私自占有,方法release(伴隨getState、setState)完全釋放此對象,恢復狀態值。。。

This class provides inspection, instrumentation, and monitoring methods for the internal queue, as well as similar methods for condition objects. These can be exported as desired into classes using an AbstractQueuedSynchronizer for their synchronization mechanics.Serialization of this class stores only the underlying atomic integer maintaining state, so deserialized objects have empty thread queues. Typical subclasses requiring serializability will define a readObject method that restores this to a known initial state upon deserialization.

此類為內部隊列提供檢查、檢測和監視方法,以及為條件對象提供類似方法。 這些可以根據需要使用 AbstractQueuedSynchronizer 的同步機制導出到類中。

此類的序列化僅存儲底層原子整數維護狀態,因此反序列化的對象具有空線程隊列。 需要可序列化的子類需要定義一個 readObject 方法,該方法在反序列化時將其恢復到已知的初始狀態。

To use this class as the basis of a synchronizer, redefine the following methods, as applicable, by inspecting and/or modifying the synchronization state using getState, setState and/or compareAndSetState:

tryAcquiretryReleasetryAcquireSharedtryReleaseSharedisHeldExclusively

子類重新這些方法,這些方法內部使用getState, setState來檢查同步狀態,使用compareAndSetState來修改同步狀態

Each of these methods by default throws UnsupportedOperationException. Implementations of these methods must be internally thread-safe, and should in general be short and not block. Defining these methods is the only supported means of using this class. All other methods are declared final because they cannot be independently varied.

You may also find the inherited methods from AbstractOwnableSynchronizer useful to keep track of the thread owning an exclusive synchronizer. You are encouraged to use them -- this enables monitoring and diagnostic tools to assist users in determining which threads hold locks.

AQS繼承AbstractOwnableSynchronizer,這個類用來追蹤持有獨占同步器的線程

Even though this class is based on an internal FIFO queue, it does not automatically enforce FIFO acquisition policies. The core of exclusive synchronization(獨占同步機制) takes the form:

Acquire: while (!tryAcquire(arg)) { enqueue thread if it is not already queued; possibly block current thread; } Release: if (tryRelease(arg)) unblock the first queued thread;

(Shared mode is similar but may involve cascading signals.)

public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } public final boolean release(int arg) { if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 0) unparkSuccessor(h); return true; } return false; }

Because checks in acquire are invoked before enqueuing, a newly acquiring thread may barge ahead of others that are blocked and queued.(不公平,最壞的情況是饑餓) However, you can, if desired, define tryAcquire and/or tryAcquireShared to disable barging by internally invoking one or more of the inspection methods, thereby providing a fair FIFO acquisition order. In particular, most fair synchronizers can define tryAcquire to return false if hasQueuedPredecessors (a method specifically designed to be used by fair synchronizers) returns true. Other variations are possible.

方法acquire中檢查在入隊之前,一個新的acquiring線程可能搶占到拿下入隊的阻塞的線程前面,這是不公平的。最壞情況是線程饑餓。AQS子類可以重寫tryAcquire and/or tryAcquireShared去禁止搶占,通過別的監管方法,進而提供公平的FIFO隊列.In particular, 如果 hasQueuedPredecessors(一種專門設計用于公平同步器使用的方法)返回 true,大多數公平同步器可以定義 tryAcquire 以返回 false。 其他變化也是可能的。

道格李給出一個鎖使用AQS子類的例子,這是一個非重入的同步器

class Mutex implements Lock, java.io.Serializable { // Our internal helper class private static class Sync extends AbstractQueuedSynchronizer { // Reports whether in locked state protected boolean isHeldExclusively() { return getState() == 1; } // Acquires the lock if state is zero public boolean tryAcquire(int acquires) { assert acquires == 1; // Otherwise unused if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } // Releases the lock by setting state to zero protected boolean tryRelease(int releases) { assert releases == 1; // Otherwise unused if (getState() == 0) throw new IllegalMonitorStateException(); setExclusiveOwnerThread(null); setState(0); return true; } // Provides a Condition Condition newCondition() { return new ConditionObject(); } // Deserializes properly private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } } // The sync object does all the hard work. We just forward to it. private final Sync sync = new Sync(); public void lock() { sync.acquire(1); } public boolean tryLock() { return sync.tryAcquire(1); } public void unlock() { sync.release(1); } public Condition newCondition() { return sync.newCondition(); } public boolean isLocked() { return sync.isHeldExclusively(); } public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } } /**Here is a latch class that is like a CountDownLatch except that it only requires a single signal to fire. Because a latch is non-exclusive, it uses the shared acquire and release methods. */ class BooleanLatch { private static class Sync extends AbstractQueuedSynchronizer { boolean isSignalled() { return getState() != 0; } protected int tryAcquireShared(int ignore) { return isSignalled() ? 1 : -1; } protected boolean tryReleaseShared(int ignore) { setState(1); return true; } } private final Sync sync = new Sync(); public boolean isSignalled() { return sync.isSignalled(); } public void signal() { sync.releaseShared(1); } public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } }

AQS子類一般作為內部幫助類,外部類使用AQS來提供對外接口

注明:本文章來源于互聯網,如侵權請聯系客服刪除!