title: Java: synchronized put() with a list of objects
body: <p>I'm using a LinkedBlockingQueue to handle message objects from other threads.  For example, I have something like this:</p>
  
  <pre><code>LinkedBlockingQueue&lt;Message&gt; message_queue = new LinkedBlockingQueue&lt;Message&gt;();
  
  public void run(){
      while(true){
          Message m = message_queue.take();
          handle_message(m);
      }
  }
  </code></pre>
  
  <p>When I add a new message from another thread, I call message_queue.put(m).  No problem!  My question is this:</p>
  
  <p>How do I synchronize the addition of a SET of messages all at once?  Let's say I want to do this:</p>
  
  <pre><code>Message[] messages = {/* some list of message objects */};
  for (Message m : messages){
      message_queue.put(m);
  }
  </code></pre>
  
  <p>The problem is that another thread could be doing the same thing, and the messages from one thread are not guaranteed to be queued exactly as I intend.  Messages from the competing thread can be "interleaved" inbetween (i.e. the actual sequence could end up being A, A, B, B, A, B instead of the intended A, A, A, B, B, B)  I know I could put the loop in the "put" example into a "synchronized(message_queue){}" block, but would I also need to put that same block around the call to .take()?  And obviously, I can't do that, as it would instantly create a deadlock situation, since take() blocks until a new Message is put(), which cannot happen when locked by synchronization.  Can I skip the synchronized block on the take() call, having only a synchronized block on the put loop, and get the desired effect?  Thanks!</p>