title: Synchronizing queue in Java on multiple threads
body: <p>I understand the concept of synchronizing, but I'm now sure about why is it implemented that way, so I need a little help in here:</p>
  
  <p>I have 2 threads: </p>
  
  <p><code>PeriodicalThread</code> will receive data periodically (let's say each 5 seconds) and put it in a <code>Queue</code> (using <code>ArrayDeque</code> for the moment, but I don't know if any other <code>Queue</code> implementation will work better)</p>
  
  <p><code>ProccessThread</code> will constantly check on the <code>Queue</code> to see if it is empty. If it is not empty, it will process the data <strong>(FIFO)</strong>.</p>
  
  <p>So, at first my implementation would be:</p>
  
  <pre><code>// Both threads are inner class so they have access to Queue
  
  private Queue queue;
  private boolean isReadyToProccess;
  
  
  class PeriodicalThread extends Thread {
      public void run() {
          while(true) {
             if(isNewDataAvailable) {
                  // create Data object
                  queue.add(data);
             }
          }
      }
  }
  
  class ProcessThread extends Thread {
      public void run() {
          while(true) {
             if(!queue.isEmpty() &amp;&amp; isReadyToProccess) {
                 Data data = queue.poll();
                 processData(data);
             }
          }
      }
  }
  
  private void processData(Data data) {
      // this method send data over network, and the server response callback
      // changes isReadyToProcess value to true.
  }
  </code></pre>
  
  <p>Then when wanting to handle <strong>synchronization</strong>, I wouldn't know If I should use a <code>lock</code> object (and how is it implemented) or if there is already a package <code>Queue</code> implementation that is thread-safe (because of the <code>add()</code> and <code>poll()</code> methods)</p>
  
  <p><strong>Edit:</strong> I forgot about the flag <code>isReadyToProcess</code> indicating next queue <code>Data</code> object is... well, ready to be proccessed. This flag should be synchronized also.</p>