分享

深入java并发Lock一

 dtl乐学馆 2015-01-14
  java有像syncronized这样的内置锁,但为什么还需要lock这样的外置锁?

性能并不是选择syncronized或者lock的原因,jdk6中syncronized的性能已经与lock相差不大。

如果要选择lock的话,会基于lock拥有的几个优点(内置锁所不具备):
 1.如果希望当获取锁时,有一个等待时间,不会无限期等待下去。
  2.希望当获取不到锁时,能够响应中断
  3.当读多,写少的应用时,希望提高性能
 4.获取不到锁时,立即返回false。获取到锁时返回true。

lock接口定义以下方法:
public interface Lock {

    void lockInterruptibly() throws InterruptedException;

    boolean tryLock();

    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

    void unlock();

    Condition newCondition();
}

其中lockInterruptibly(),表明加锁时,当前拥有这个锁的线程可被中断。
tryLock()则用于尝试获取锁,能获取返回true,否则返回false。
tryLock(long time, TimeUnit unit),与tryLock类似,只是会尝试一定的时间后再根据是否能够获取锁返回相应的true或false。
unlock()用于拥有锁的线程释放锁。

newCondition()方法之后介绍。

有些操作需要满足一些前提条件才能进行,这就涉及状态并发的控制。
如一个有界缓存,对于存放操作需要判断当前缓存是否满了,满了的话需要阻塞等待。不满则放入数据,并唤醒等待取数据的线程。
对于取操作,需要判断当前缓存是否非空,为空则阻塞等待。不为空则取出数据,并唤醒阻塞的进行存放操作的线程。

考虑,这样的一个有界缓存如何设计?

首先对于存放数据的数据结构可以是数组或者是一个链表。
这里我们假设选择数组。
然后定义两个操作方法,一个是存放数据到缓存的方法put,一个是取数据的方法take。
还需要一个int型的count代表当前已有元素数量,int型的header用于指向当前要取元素的位置,一个tail用于指向当前存放元素的位置。
接着关键是要保证put与take在并发的情况下,保证数据操作完整性,不出现异常行为。
这就需要保证并发调用put操作时是加锁互斥的,否则会发生以下情况:
当前缓存数组大小为3,当前已经在缓存的数据有两个。
这时线程一进行以下存放步骤操作:
  1.线程一首先判断当前数组是否未满
  2.这时未满接着线程一往缓存存数据
但当线程一进行第二步操作:往缓存存数据时,线程二提前将数据放入缓存,这时数组大小为3
这样线程一再往数组放数据时,就超出数组长度了。

所以put操作必需同步控制。

其次,由于需要保存count当前元素数量,因此也需要保证存取操作put及take方法互斥。

简单实现上述buffer代码如下:

  1. public class BoundedBuffer{  
  2.   
  3.     private static final BoundedBuffer bufferInstance = new BoundedBuffer();  
  4.   
  5.     private static final int DEFAULT_BUFFER_SIZE = 1;  
  6.   
  7.     private final Object[] buffer = new Object[DEFAULT_BUFFER_SIZE];  
  8.   
  9.     private static final int EMPTY = 0;  
  10.   
  11.     private int header;  
  12.   
  13.     private int tail;  
  14.   
  15.     private int count;  
  16.       
  17.     private BoundedBuffer(){  
  18.           
  19.     }  
  20.       
  21.     public static BoundedBuffer getInstanceOfBuffer(){  
  22.         return bufferInstance;  
  23.     }  
  24.   
  25.     public synchronized void put(Object obj) throws InterruptedException {  
  26.         while (count >= DEFAULT_BUFFER_SIZE) {  
  27.             System.out.println("the buffer is full,wait for a moment,thread:"  
  28.                     + Thread.currentThread().getId());  
  29.             wait();  
  30.         }  
  31.         if (tail >= DEFAULT_BUFFER_SIZE) {  
  32.             tail = 0;  
  33.         }  
  34.         System.out.println("success to put the data:"+obj+" into the buffer,thread:"+Thread.currentThread().getId());  
  35.         buffer[tail++] = obj;  
  36.   
  37.         count++;  
  38.   
  39.         // then we invoke the thread in the notEmptyCondition wait queue  
  40.         notifyAll();  
  41.     }  
  42.   
  43.     /**  
  44.      * take the data from header of the queue  
  45.      *   
  46.      * @return  
  47.      * @throws InterruptedException  
  48.      */  
  49.     public synchronized Object take() throws InterruptedException {  
  50.         Object res;  
  51.         while (count <= EMPTY) {  
  52.             System.out.println("the buffer is empty,just wait a moment,thread:"  
  53.                     + Thread.currentThread().getId());  
  54.             wait();  
  55.         }  
  56.         res = buffer[header];  
  57.         if (++header >= DEFAULT_BUFFER_SIZE) {  
  58.             header = 0;  
  59.         }  
  60.         count--;  
  61.         if(count<0){  
  62.             count=0;  
  63.         }  
  64.           
  65.         //notify the thread which wait to put the data to buffer when the buffer is null   
  66.         notifyAll();  
  67.           
  68.         return res;  
  69.     }  
  70.   
  71.     private static class BufferProducor implements Runnable {  
  72.   
  73.         private Object target;  
  74.   
  75.         public void run() {  
  76.             try {  
  77.                 BoundedBuffer.getInstanceOfBuffer().put(target);  
  78.             } catch (InterruptedException e) {  
  79.                 e.printStackTrace();  
  80.                 System.out  
  81.                         .println("client interrupt the task added the data to the buffer");  
  82.             }  
  83.         }  
  84.   
  85.         public void setTarget(Object target) {  
  86.             this.target = target;  
  87.         }  
  88.   
  89.     }  
  90.   
  91.     private static class BufferConsumer implements Runnable {  
  92.         public void run() {  
  93.             try {  
  94.                 Object res = BoundedBuffer.getInstanceOfBuffer().take();  
  95.                 System.out.println("we get the result from buffer:" + res);  
  96.             } catch (InterruptedException e) {  
  97.                 e.printStackTrace();  
  98.                 System.out  
  99.                         .println("client interrupt the task take the data from the buffer");  
  100.             }  
  101.         }  
  102.   
  103.     }  
  104.   
  105.     public static void main(String[] args) {  
  106.   
  107.         ExecutorService service = Executors.newFixedThreadPool(5);  
  108.   
  109.         BufferProducor bufferProducor1 = new BufferProducor();  
  110.         bufferProducor1.setTarget("a");  
  111.   
  112.         BufferProducor bufferProducor2 = new BufferProducor();  
  113.         bufferProducor2.setTarget("b");  
  114.   
  115.         BufferConsumer bufferConsumer1 = new BufferConsumer();  
  116.         BufferConsumer bufferConsumer2 = new BufferConsumer();  
  117.   
  118.         service.submit(bufferProducor1);  
  119.         service.submit(bufferProducor2);  
  120.         service.submit(bufferConsumer1);  
  121.         service.submit(bufferConsumer2);  
  122.     }  
  123. }  

分析这个程序,有什么问题?
首先程序想实现通过wait方法来阻塞存取线程,通过notifyAll来唤醒存取线程。
这里说明下,由于用的是内置锁syncronized,并且当前锁对象是bufferInstance单例实例。所以当调用wait时,当前线程被挂起放入当前bufferInstance相关的内置条件队列当中。后续调用notifyAll则是将这个条件队列中所有阻塞的线程唤醒。
这样由于只有一个条件队列用于存放阻塞的线程,所以存数据线程及取数据线程都是放在一个阻塞条件队列当中。

notifyAll会唤醒所有阻塞的线程,比如,当前在阻塞队列中有10个等待存数据到buffer的线程。
然后有一个消费线程从元素满的buffer中取出数据,并通过notifyAll唤醒所有在阻塞队列中的线程,然后在阻塞队列中的三个线程都醒了,其中一个线程可以将数据放入buffer,其它9个线程由于buffer空间已满,又被挂起进入到阻塞队列。


如果需要优化这段代码性能的话,一种是只在引起存取线程阻塞的状态变化上才进行唤醒操作,即如果取操作线程要唤醒被阻塞的存操作线程,条件是:取操作线程进入take方法时,buffer元素是满的,然后取线程取出一个元素,使得buffer有空闲空间让存线程存数据。

进一步优化的话,能不能每次只唤醒一个线程?
对于现在一个条件队列存放两种类型的阻塞线程来讲,这样是不允许的。
考虑如果当前buffer可以容纳一个元素,这时先有三个存线程往buffer放数据,这样其中两个线程被阻塞到条件队列。
然后这时一个取数据线程,从buffer取走一个数据并调用notify方法唤醒条件队列中一个存线程。
这样条件队列中还有一个存线程。
接着存线程要存数据到buffer,但有一个取线程先来到take方法然后发现buffer还是空的,然后这个取线程被放入到了条件队列。
这样条件队列中就有一个存线程及一个取线程。
然后刚才被唤醒的存线程继续做存操作,然后调用notify唤醒条件队列中的一个线程,由于内置锁的条件队列取操作是非公平的因此很有可能这时唤醒的是条件队列中的
存线程。事实上是没有意义的。

所有对于以上一个条件队列中有两种等待不同条件被阻塞的线程的情况时,不能用单个notify。

如果想用单个notify就要想办法将之前阻塞的存线程与取线程分别放在两个队列。
这就要用到Lock的newCondition方法。

重构代码如下:

  1. public class ConditionBoundedBuffer {  
  2.       
  3.     private static final ConditionBoundedBuffer bufferInstance = new ConditionBoundedBuffer();  
  4.   
  5.     private static final int DEFAULT_BUFFER_SIZE = 1;  
  6.   
  7.     private final Object[] buffer = new Object[DEFAULT_BUFFER_SIZE];  
  8.   
  9.     private static final int EMPTY = 0;  
  10.   
  11.     private final Lock lock = new ReentrantLock();  
  12.   
  13.     private int header;  
  14.   
  15.     private int tail;  
  16.   
  17.     private int count;  
  18.   
  19.     private final Condition notFullCondition = lock.newCondition();  
  20.   
  21.     private final Condition notEmptyCondition = lock.newCondition();  
  22.       
  23.     private ConditionBoundedBuffer(){  
  24.           
  25.     }  
  26.       
  27.     public static ConditionBoundedBuffer getInstanceOfConditionBoundedBuffer(){  
  28.         return bufferInstance;  
  29.     }  
  30.   
  31.     public void put(Object obj) throws InterruptedException {  
  32.         lock.lock();  
  33.         try {  
  34.             while (count == DEFAULT_BUFFER_SIZE) {  
  35.                 System.out.println("the buffer is full,wait for a moment for putting ["+obj+"] to the buffer"+",thread:"+Thread.currentThread().getId());  
  36.                 notFullCondition.await();  
  37.             }  
  38.             if (tail >= DEFAULT_BUFFER_SIZE) {  
  39.                 tail = 0;  
  40.             }  
  41.             buffer[tail++] = obj;  
  42.               
  43.             count++;  
  44.               
  45.             System.out.println("success put the data ["+obj+"] to buffer,thread:"+Thread.currentThread().getId());  
  46.   
  47.             // then we invoke the thread in the notEmptyCondition wait queue  
  48.             notEmptyCondition.signal();  
  49.   
  50.         } finally {  
  51.             lock.unlock();  
  52.         }  
  53.     }  
  54.   
  55.     /**  
  56.      * take the data from header of the queue  
  57.      *   
  58.      * @return  
  59.      * @throws InterruptedException  
  60.      */  
  61.     public Object take() throws InterruptedException {  
  62.         lock.lock();  
  63.         Object res;  
  64.         try {  
  65.             while (count == EMPTY) {  
  66.                 System.out.println("the buffer is empty,just wait a moment,thread:"+Thread.currentThread().getId());  
  67.                 notEmptyCondition.await();  
  68.             }  
  69.             res = buffer[header];  
  70.             if (++header >= DEFAULT_BUFFER_SIZE) {  
  71.                 header = 0;  
  72.             }  
  73.               
  74.             count--;  
  75.             if(count<EMPTY){  
  76.                 count=0;  
  77.             }  
  78.               
  79.             notFullCondition.signal();  
  80.   
  81.         } finally {  
  82.             lock.unlock();  
  83.         }  
  84.         return res;  
  85.     }  
  86.   
  87.     private static class BufferProducor implements Runnable {  
  88.   
  89.         private Object target;  
  90.   
  91.         public void run() {  
  92.             try {  
  93.                 ConditionBoundedBuffer.getInstanceOfConditionBoundedBuffer().put(target);  
  94.             } catch (InterruptedException e) {  
  95.                 e.printStackTrace();  
  96.                 System.out  
  97.                         .println("client interrupt the task added the data to the buffer");  
  98.             }  
  99.         }  
  100.   
  101.         public void setTarget(Object target) {  
  102.             this.target = target;  
  103.         }  
  104.   
  105.     }  
  106.   
  107.     private static class BufferConsumer implements Runnable {  
  108.         public void run() {  
  109.             try {  
  110.                 Object res = ConditionBoundedBuffer.getInstanceOfConditionBoundedBuffer().take();  
  111.                 System.out.println("we get the result from buffer:" + res);  
  112.             } catch (InterruptedException e) {  
  113.                 e.printStackTrace();  
  114.                 System.out  
  115.                         .println("client interrupt the task take the data from the buffer");  
  116.             }  
  117.         }  
  118.   
  119.     }  
  120.   
  121.     public static void main(String[] args) {  
  122.           
  123.         ExecutorService service=Executors.newFixedThreadPool(5);  
  124.           
  125.         BufferProducor bufferProducor1=new BufferProducor();  
  126.         bufferProducor1.setTarget("a");  
  127.           
  128.         BufferProducor bufferProducor2=new BufferProducor();  
  129.         bufferProducor2.setTarget("b");  
  130.           
  131.         BufferConsumer bufferConsumer1=new BufferConsumer();  
  132.         BufferConsumer bufferConsumer2=new BufferConsumer();  
  133.           
  134.         service.submit(bufferProducor1);  
  135.         service.submit(bufferProducor2);  
  136.         service.submit(bufferConsumer1);  
  137.         service.submit(bufferConsumer2);  
  138.     }  
  139. }  

接下去的任务是搞清楚,lock内部实现原理,整个实现主要组件组成,学习其中的一些优秀想法,设计。



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多