JAVA並發--並發基礎

來源:互聯網
上載者:User

標籤:衝突   ant   共用   同步器   share   ext   return   exclusive   and   

並發基礎裡主要明白下CAS和AQS吧CAS:Compare And Swap 比較然後交換AQS:AbstractqueuedSynchronizer抽象的隊列式同步器 一、CAS CAS在很多無鎖的並發裡使用。無鎖並發的意思就是,用不加鎖的方式實現並行作業,這一波操作是不是很666啊通常加鎖操作(無論是synchronized還是Lock)都是比較悲觀的認為被鎖住的部分(無論是對象、方法還是代碼塊)每一次操作都會引起資源競爭。而CAS就比較樂觀了,他認為對資源的訪問是沒有衝突的,既然沒有衝突就應該被友好的訪問。所有訪問的線程走到這一塊的時候都不需要停下來等待其它線程釋放資源。 那CAS是哪兒來的樂觀呢?就是通過比較然後交換的思想。 CAS演算法:包含三個參數(V,E,N),其中,V表示要更新的變數,E表示預期的變數,N表示新值。若且唯若V值等於E值時,將V值更新為N值。並返回V值。 對一個線程L來講,他要去更新一個值的時候(V),他首Crowdsourced Security Testing道這個值應該等於E,更新之前他先去比較一下,當確認V值等於E了,他就認為這個值沒有被其他線程修改過,藍後,再對V進行更新,更新為N值。 CAS的應用之一是jdk的atomic包。比如AtomicInteger compareAndSet是主要使用的方法,當 public final boolean compareAndSet(int expect, int update) {    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);} unsafe的 compareAndSwapInt方法是native的,會調用底層作業系統完成對值的修改  CAS會遇到一個無法解決的問題,即ABA問題。V值在處理中被多次修改。意思是說對於之前的線程L來說,他去更新V值的時候。確認V值等於E不能完全確認這個值沒有被其它線程修改過。比如線程L1將V值改成V1,線程L2將V值又改回了V值。V值經曆了兩次修改,但是對於L線程來說,這個值沒有修改過。But,V值其實進行了多次更新。 對於ABA問題,解決方案是設定一個時間戳記,每次修改成功後更新時間戳記。對於V值的預期值E和預期時間戳記都滿足時才對V值進行更新。  二、AQSAQS是java.util.concurrent.locks包下的AbstractQueuedSynchronizer類。AQS核心是通過共用變數同步狀態,變數的狀態由子類維護,AQS架構主要做的是:線程阻塞隊列的維護線程阻塞和喚醒 * <pre>*         +------+ prev +-----+         +-----+* head |          | <---- |          | <---- |          | tail*         +------+         +-----+          +-----+* </pre>摘自jdk源碼說明,是LCH隊列鎖的說明。LCH隊列鎖是一個FIFO隊列,每個節點是一個等待線程,其前繼節點(pre)釋放鎖之後就可以獲得鎖了。AbstractQueuedSynchronizer通過內部類Node來維護這個隊列。 AbstractQueuedSynchronizer成員變數維護一個Node類型的head,一個Node類型的tail以及狀態state。維護對LCH隊列的入隊出隊操作以及對state狀態的修改。 其中,共用變數state的修改是通過unsafe的CAS來操作的。protected final boolean compareAndSetState(int expect, int update) {    // See below for intrinsics setup to support this    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);}  /*** 使用當前線程和指定的模式建立Node節點,並對節點做入隊操作** @param mode模式 Node.EXCLUSIVE for exclusive(獨佔模式,只有一個線程能執行,比如ReetrantLock),                                    Node.SHARED for shared(共用模式,多個線程可同時執行,比如Semaphere/CountDownLatch)* @return the new node*/private Node addWaiter(Node mode) {    Node node = new Node(Thread.currentThread(), mode);    // Try the fast path of enq; backup to full enq on failure    Node pred = tail;    if (pred != null) {        node.prev = pred;        if (compareAndSetTail(pred, node)) {            pred.next = node;            return node;        }    }    enq(node);    return node;} 其中,入隊的操作如下/*** Inserts node into queue, initializing if necessary. See picture above.* @param node the node to insert* @return node‘s predecessor*/private Node enq(final Node node) {    for (;;) {        Node t = tail;        if (t == null) { // Must initialize            if (compareAndSetHead(new Node()))                tail = head;        } else {            node.prev = t;            if (compareAndSetTail(t, node)) {                t.next = node;                return t;            }        }    }} AbstractQueuedSynchronizer主要有兩個方法:acquire()和release()acquire方法用來擷取鎖,返回true說明線程擷取成功繼續執行,一旦返回false則線程加入到等待隊列中,等待被喚醒,release方法用來釋放鎖。 一般來說實現的時候這兩個方法被封裝為lock和unlock方法。  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;} 以下四個方法由子類去實現protected boolean tryAcquire(int arg)protected boolean tryRelease(int arg)protected int tryAcquireShared(int arg)protected boolean tryReleaseShared(int arg)  

JAVA並發--並發基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.