JAVA并发编程学习笔记之AQS源码分析(超时、中断与其他)

(非原创)

中断

JAVA中并没有好的中断线程的方式,早期引入的Thead.stop()和Thread.resume()容易导致死锁(参考:http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html),已经不推荐使用。

JAVA线程提供了协作式中断,何为协作是中断,是相对抢占式中断而言的,简单来讲就是设置一个中断标志位,不停地检查这个标志位的状态,如果检查到线程中断,就中断线程。JVM线程内部维护着一个中断标志,程序员不能直接操作这个中断标志位,只能通过线程的以下几个方法设置中断位:

 

[html]   view plain copy print ?
  1. public void interrupt()  
  2. public static boolean interrupted()   
  3. private native boolean isInterrupted(boolean ClearInterrupted);  
  4. public boolean isInterrupted()  

 

AQS中提供了支持中断的方法

 

[html]   view plain copy print ?
  1. private void doAcquireInterruptibly(int arg) throws InterruptedException;  
  2. private void doAcquireSharedInterruptibly(int arg) throws InterruptedException;   
  3. private boolean doAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException;  

这几个方法都抛出了InterruptedException,这些方法都会先出处中断异常,处理的代码如下:

 

 

[html]   view plain copy print ?
  1. if (Thread.interrupted())  
  2.     throw new InterruptedException();  

我们还看到有些方法并没有申请抛出InterruptedException,当它被中断时,设置了线程的中断位。

 

 

[html]   view plain copy print ?
  1. private static void selfInterrupt() {  
  2.     Thread.currentThread().interrupt();  
  3. }  

超时

AQS与JVM内置锁的一个不同点在于AQS中提供了超时机制,即线程在等待一定时间后会立即返回。下面以doAcquireNanos为例来分析:
[java]   view plain copy print ?
  1. private boolean doAcquireNanos(int arg, long nanosTimeout)  
  2.     throws InterruptedException {  
  3.     long lastTime = System.nanoTime();  
  4.     final Node node = addWaiter(Node.EXCLUSIVE);  
  5.     boolean failed = true;  
  6.     try {  
  7.         for (;;) {  
  8.             final Node p = node.predecessor();  
  9.             if (p == head && tryAcquire(arg)) {  
  10.                 setHead(node);  
  11.                 p.next = null// help GC  
  12.                 failed = false;  
  13.                 return true;  
  14.             }  
  15.             if (nanosTimeout <= 0)  
  16.                 return false;  
  17.             if (shouldParkAfterFailedAcquire(p, node) &&  
  18.                 nanosTimeout > spinForTimeoutThreshold)  
  19.                 LockSupport.parkNanos(this, nanosTimeout);  
  20.             long now = System.nanoTime();  
  21.             nanosTimeout -= now - lastTime;  
  22.             lastTime = now;  
  23.             if (Thread.interrupted())  
  24.                 throw new InterruptedException();  
  25.         }  
  26.     } finally {  
  27.         if (failed)  
  28.             cancelAcquire(node);  
  29.     }  
  30. }  
1、首先取得当前系统时间,在循环等待的过程中,如果剩余时间<=0立即返回;
2、如果剩余时间>0,就用总时间减去一次循环耗费的时间,继续阻塞;
3、如果在这期间线程被中断,就抛出中断异常,如果有其他异常产生,就取消这次获取。
 

取消

取消获取的逻辑比较复杂,下面来分析一下:
[java]   view plain copy print ?
  1. private void cancelAcquire(Node node) {  
  2.       // Ignore if node doesn't exist  
  3.       if (node == null)  
  4.           return;  
  5.   
  6.       node.thread = null;  
  7.   
  8.       // Skip cancelled predecessors  
  9.       Node pred = node.prev;  
  10.       while (pred.waitStatus > 0)  
  11.           node.prev = pred = pred.prev;  
  12.   
  13.       // predNext is the apparent node to unsplice. CASes below will  
  14.       // fail if not, in which case, we lost race vs another cancel  
  15.       // or signal, so no further action is necessary.  
  16.       Node predNext = pred.next;  
  17.   
  18.       // Can use unconditional write instead of CAS here.  
  19.       // After this atomic step, other Nodes can skip past us.  
  20.       // Before, we are free of interference from other threads.  
  21.       node.waitStatus = Node.CANCELLED;  
  22.   
  23.       // If we are the tail, remove ourselves.  
  24.       if (node == tail && compareAndSetTail(node, pred)) {  
  25.           compareAndSetNext(pred, predNext, null);  
  26.       } else {  
  27.           // If successor needs signal, try to set pred's next-link  
  28.           // so it will get one. Otherwise wake it up to propagate.  
  29.           int ws;  
  30.           if (pred != head &&  
  31.               ((ws = pred.waitStatus) == Node.SIGNAL ||  
  32.                (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&  
  33.               pred.thread != null) {  
  34.               Node next = node.next;  
  35.               if (next != null && next.waitStatus <= 0)  
  36.                   compareAndSetNext(pred, predNext, next);  
  37.           } else {  
  38.               unparkSuccessor(node);  
  39.           }  
  40.   
  41.           node.next = node; // help GC  
  42.       }  
  43.   }  
1、首先取得当前结点的前趋结点,如果前趋结点也被取消直接跳过,继续向前找非取消的结点;
2、将当前结点设置为取消状态;
3、如果当前结点是队尾结点,则将当前结点从队尾移除;否则执行4;
4、找到当前结点的继任结点,前趋的next指针指向继任结点(pred->next=current->next);
5、当前结点的next指针指向自己,前面提到这一方面为了回收,一方面为了使isOnSyncQueue方法简单。
 

其他

AQS还提供了一些线程监控的方法:
[java]   view plain copy print ?
  1. //获取哪些线程在等待  
  2. protected final Collection<Thread> getWaitingThreads();   
  3. //获取等待队列的长度  
  4. protected final int getWaitQueueLength();   
  5. //是否有线程在等待  
  6. protected final boolean hasWaiters()  
  7. //是否拥有同步器  
  8. final boolean isOwnedBy(AbstractQueuedSynchronizer sync)  
  9. //是否在同步队列中  
  10. final boolean isOnSyncQueue(Node node)  
  11. //支持共享模式的线程  
  12. public final Collection<Thread> getSharedQueuedThreads()  
  13. //支持独占模式的线程  
  14. public final Collection<Thread> getExclusiveQueuedThreads();  

参考资料:

猜你喜欢

转载自201209124112.iteye.com/blog/2076323