title: java concurrency: multi-producer one-consumer
body: <p>I have a situation where different threads populate a queue (producers) and one consumer retrieve element from this queue. My problem is that when one of these elements are retrieved from the queue some is missed (missing signal?). The producers code is:</p>
  
  <pre><code>class Producer implements Runnable {
  
      private Consumer consumer;
  
      Producer(Consumer consumer) { this.consumer = consumer; }
  
      @Override
  public void run() {
      consumer.send("message");
    }
  }
  </code></pre>
  
  <p>and they are created and run with:</p>
  
  <pre><code>ExecutorService executor = Executors.newSingleThreadExecutor();
  for (int i = 0; i &lt; 20; i++) {
    executor.execute(new Producer(consumer));
  }
  </code></pre>
  
  <p>Consumer code is:</p>
  
  <pre><code>class Consumer implements Runnable {
  
  private Queue&lt;String&gt; queue = new ConcurrentLinkedQueue&lt;String&gt;();
  
  void send(String message) {
      synchronized (queue) {
          queue.add(message);
          System.out.println("SIZE: " + queue.size());
          queue.notify();
      }
  }
  
  @Override
  public void run() {
      int counter = 0;
      synchronized (queue) {
      while(true) {
          try {
              System.out.println("SLEEP");
                  queue.wait(10);
          } catch (InterruptedException e) {
                  Thread.interrupted();
          }
          System.out.println(counter);
          if (!queue.isEmpty()) {             
              queue.poll();
              counter++;
          }
      }
      }
  }
  
  }
  </code></pre>
  
  <p>When the code is run I get sometimes 20 elements added and 20 retrieved, but in other cases the elements retrieved are less than 20. Any idea how to fix that?</p>