java.util.concurrent 包下的 Synchronizer 框架

看完书 java concurrency in practice 当然是想找点啥好玩的东东玩玩。 当看到了Doug Lee 的论文 << The java.util.concurrent Synchronizer Framework >> 大呼来的太晚喔, 前段时间看那个ReentrantLock 的代码真的是痛苦啊,不过现在也不晚不是。  呵呵, 上菜:这个框架的核心是一个AbstractQueuedSynchronizer 类 (下面简称AQS)  它基本上的思路是:

 

  •     采用Template Method Pattern.  它实现了non-contended 的synchronization 算法;
  •     继承 它的Subclass  一般不直接作为Synchronzier, 而是作为私有的实现 被用来delegate.  比如 他举了个例子:

     class Mutex implements Lock, java.io.Serializable {

Java代码   收藏代码
  1. // Our internal helper class  
  2. private static class Sync extends AbstractQueuedSynchronizer {  
  3.   .....  
  4. }  
  5.   
  6. // The sync object does all the hard work. We just forward to it.  
  7. private final Sync sync = new Sync();  
  8.   
  9. public void lock()                { sync.acquire(1); }  
  10. public boolean tryLock()          { return sync.tryAcquire(1); }  
  11. public void unlock()              { sync.release(1); }  
  12. public Condition newCondition()   { return sync.newCondition(); }  
  13. public boolean isLocked()         { return sync.isHeldExclusively(); }  
  14. public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }  
  15. public void lockInterruptibly() throws InterruptedException {  
  16.   sync.acquireInterruptibly(1);  
  17. }  
  18. public boolean tryLock(long timeout, TimeUnit unit)  
  19.     throws InterruptedException {  
  20.   return sync.tryAcquireNanos(1, unit.toNanos(timeout));  
  21. }  

 

在这个 AQS 类中 提供了 两大类方法 

      acquire   其中还包括  非阻塞的 tryAcquire;  带 time out 的;可以通过interruption 来cancellality 的。

 

      release   相对简单点, 因为在调用release 方法的时候基本上暗含了个意思当前的线程是获得了锁的。  

 

在JUC 包中没有为各种Synchronizer 类提供统一的API 比如 Lock.lock, Semaphore.acquire, CountDownLatch.await  and  FutureTask.get 都是映射到这个AQS 的 acquire 方法。 

 

要实现一个Synchronizer 的基本思路非常直接的 

  acquire 操作

    采用CAS 操作去更新同步状态  如果不成功  {

enqueue 当前线程

        block 当前线程

}

   dequeue  当前线程  if it was queued      // 此时应该是当前线程被别的线程 release 来唤醒的。

 

 

release 操作 :

    更新同步状态, 此时可以直接 set 而不通过 CAS。

    假如 等待队列中还有线程  unblock  one or more

 

 

要支持这些操作 需要 三类基本的组件:

 1,   Atomically managing synchronization state。   这个通过  

private   volatile  int   state;

         在处理acquire 的时候基本是通过用CAS 实现的  compareAndSetState 来

 

 2,   Block /Unblock 线程 。 这个是通过 JUC 里面的一个封装类 LockSupport.park / unpark 来实现的。LockSupport 都deleget 到了 Unsafte 对应的方法

 

3, 维护 一个队列来存放 等待线程。 这个是通过一个 CLH queue 的变种。 它是一种linked queue 的通过 head 和tail 。 

 

三个里面最复杂的就是这个 CLH queue 的维护了, queue 中节点被定义为  :

   static final class Node {

Java代码   收藏代码
  1. volatile int waitStatus;  
  2. volatile Node prev;  
  3. volatile Node next;  
  4. volatile Thread thread;  
  5.   
  6. Node nextWaiter;  
  7. final boolean isShared() {  
  8.     return nextWaiter == SHARED;  
  9. }  
  10.   
  11. final Node predecessor() throws NullPointerException {  
  12.     Node p = prev;  
  13.     if (p == null)  
  14.         throw new NullPointerException();  
  15.     else  
  16.         return p;  
  17.     }  
  18.   
  19. Node() {    // Used to establish initial head or SHARED marker  
  20. }  
  21.   
  22. Node(Thread thread, Node mode) {     // Used by addWaiter  
  23.     this.nextWaiter = mode;  
  24.     this.thread = thread;  
  25. }  
  26.   
  27. Node(Thread thread, int waitStatus) { // Used by Condition  
  28.     this.waitStatus = waitStatus;  
  29.     this.thread = thread;  
  30. }  
 

 

AQS 中定义了 

 

Java代码   收藏代码
  1. private Node addWaiter(Node mode) {  
  2.         Node node = new Node(Thread.currentThread(), mode);  
  3.         // Try the fast path of enq; backup to full enq on failure  
  4.         Node pred = tail;  
  5.         if (pred != null) {  
  6.             node.prev = pred;  
  7.             if <span style="color: #ff0000;">(compareAndSetTail(pred, node</span>)) {  
  8.                 pred.next = node;  
  9.                 return node;  
  10.             }  
  11.         }  
  12.         enq(node);  
  13.         return node;  
  14.     }  
 

这个方法通常在 acquire 的时候如果 tryAcquire 失败就会将insert 一个 Node 到 tail 之后, 并且 node.prev 指向先前的 tail。 当然这个是在 compareAndSetTail(pred, node)  返回true 的时候比较简单, 否则就进入 enq(node) 方法 差不多也是这个逻辑 insert 一个 Node 到 tail 之后。

 

 

在 1.6.0_25 版本里面AQS 就没有在 release 的时候 通过唤醒等待队列里面head指向的线程, 然后然后该线程是在 方法里面继续resume, 基本上会 

 

if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    return interrupted;
                }。
 就是将head的下一个节点设为Head, 原来的head 呢 p.next = null,  p 不再引用任何对象, gc 就会发生作用。  这个基本上会的例外是啥呢, 新线程acquire 调用 tryAcquire 抢占成功 。 这个线程就只有继续park 了。 

基本上来讲 有了 这个 AQS  , 我们要想实现一个 Synchronizer 就比较简单了,  最简单的情况下  treAcquire , tryRelease 实现下。AQS 里面提供的需要继承的方法不是采用abstract 的方式 而是用抛出 notImplementedException的 方式, 如果像那些tryAcquireShared 之类的 在 exclusive 模式下根本就不会被调用到,  我们也就根本就不必override。  比如 先前我们所的那个 Mutex 我们只需要定义它的内部类 Sync

 

 

Java代码   收藏代码
  1. // Our internal helper class  
  2.    private static class Sync extends AbstractQueuedSynchronizer {  
  3.      // Report whether in locked state  
  4.      protected boolean isHeldExclusively() {  
  5.        return getState() == 1;  
  6.      }  
  7.   
  8.      // Acquire the lock if state is zero  
  9.      public boolean tryAcquire(int acquires) {  
  10.        assert acquires == 1// Otherwise unused  
  11.        if (compareAndSetState(01)) {  
  12.          setExclusiveOwnerThread(Thread.currentThread());  
  13.          return true;  
  14.        }  
  15.        return false;  
  16.      }  
  17.   
  18.      // Release the lock by setting state to zero  
  19.      protected boolean tryRelease(int releases) {  
  20.        assert releases == 1// Otherwise unused  
  21.        if (getState() == 0throw new IllegalMonitorStateException();  
  22.        setExclusiveOwnerThread(null);  
  23.        setState(0);  
  24.        return true;  
  25.      }  
  26.   
  27.      // Provide a Condition  
  28.      Condition newCondition() { return new ConditionObject(); }  
  29.   
  30.      
  31.    }  
 

 

这个框架是非常精巧的,  还有很多地方比如那个 ConditionObject 里面涉及到另外一个单独的condition queue。只有再慢慢的啃了。   

 

另外贴一张本人手工画的图,非常潦草多包涵了。  

 

 

AbstractQueuedSynchronizer

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值