0

In the javadoc, I saw the addAll is not thread safe for BlockingQueue, so I suppose the following code is not thread safe, but I run it for a long time, and not exception throw, could anyone explain that ? Thanks

public class Test {

  public static void main(String[] args) throws InterruptedException {
    LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    new Producer(queue).start();
    new Consumer(queue).start();
  }

  public static class Producer extends Thread {
    private LinkedBlockingQueue<String> queue;

    public Producer(LinkedBlockingQueue<String> queue) {
      this.queue = queue;
    }

    @Override
    public void run() {
      while (true) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 5; ++i) {
          list.add(i + "");
        }
        this.queue.addAll(list);
      }
    }
  }

  public static class Consumer extends Thread {
    private LinkedBlockingQueue<String> queue;
    public Consumer(LinkedBlockingQueue<String> queue) {
      this.queue = queue;
    }

    @Override
    public void run() {
      while (true) {
        List<String> result = Lists.newArrayList();
        queue.drainTo(result);
        System.out.println("Take " + result.size());
      }
    }
  }
}
Farvardin
  • 5,336
  • 5
  • 33
  • 54
zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • http://stackoverflow.com/questions/12159/how-should-i-unit-test-threaded-code – Sotirios Delimanolis Oct 11 '14 at 00:59
  • saw related question here, still a little confusing, could anyone expalin it http://stackoverflow.com/questions/6607195/thread-safety-of-blockingqueues-drainto-method – zjffdu Oct 11 '14 at 01:24

0 Answers0