title: Producer-consumer inter-thread communication
body: <p>having trouble with inter-thread communication and "solved" it by using "dummy messages" all over the place. Is this a bad idea? What are possible solutions?</p>
  
  <p>Example Problem i have.</p>
  
  <p>main thread starts a thread for processing and inserting records into database.
  main thread reads a possibly huge file and puts one record (object) after another into a blockingqueue. processing thread reads from queue and does work.</p>
  
  <p>How do I tell "processing thread" to stop? 
  Queue can be empty but work is not done and the main thread does not now either when processing thread has finished work and can't interrupt it.</p>
  
  <p>So processing thread does</p>
  
  <pre><code>while (queue.size() &gt; 0 || !Thread.currentThread().isInterrupted()) {
      MyObject object= queue.poll(100, TimeUnit.MILLISECONDS);
      if (object != null) {
          String data = object.getData();
          if (data.equals("END")) {
              break;
          }
      // do work
      }
  }
  // clean-up
  synchronized queue) {
      queue.notifyAll();
  }
  return;
  </code></pre>
  
  <p>and main thread</p>
  
  <pre><code>// ...start processing thread...
  while(reader.hasNext(){
      // ...read whole file and put data in queue...
  }
  MyObject dummy = new MyObject();
  dummy.setData("END");
  queue.put(dummy);
  //Note: empty queue here means work is done
  while (queue.size() &gt; 0) {
      synchronized (queue) {
          queue.wait(500); // over-cautios locking prevention i guess
      }
  }
  </code></pre>
  
  <p>Note that insertion must be in same transaction and transaction can't be handled
  by main thread.</p>
  
  <p>What would be a better way of doing this?
  (I'm learning and don't want to start "doing it the wrong way")</p>