title: How to properly drain a Queue with a fast producer?
body: <p>I have a situation where I am in need to drain a JMS (specifically Tibco EMS) queue. The use case is if we were to take a large outage, the queue would build up and processing it would take far too long. So rather, we want to drain the queue, and perform a coldstart type routine to get current state.</p>
  
  <p>The code I have so far to do this is as follows:</p>
  
  <pre><code> int count = 0;
      Message msg = null;
      while ((msg = connection.receive(timeout)) != null) {
          count++;
      }
      System.out.println(count + " msgs removed from queue: " + queueName);
  </code></pre>
  
  <p>Basically it loops receiving messages until <code>timeout</code> expires before a message is received, indicating the queue is empty.</p>
  
  <p>My question deals with this value of <code>timeout</code>. Suppose we have a very fast producer on the queue, setting a timeout of say 500ms seems a bit arbitrary. It is possible that we will loop indefinitely (i.e. the producer produces >= 1 message every 500ms) </p>
  
  <p>The alternative is to use receiveNoWait(). This, to my understanding, pulls a message if it is available, or returns null, with no timeout involved. However, according to <strong><a href="http://forum.spring.io/forum/spring-projects/integration/jms/11384-draining-a-jms-queue-using-spring-1-2-6" rel="nofollow">THIS</a></strong> article:</p>
  
  <blockquote>
    <p>Not all JMS providers return immediately with a message if you call receiveNoWait() and there may be messages on the broker, so its worth waiting a second or so just to be sure the queue really is drained.</p>
  </blockquote>
  
  <p>So is there a more robust way to do this from a programmatic approach? Alternatively is there a drain function that comes with Tibco EMS admin? </p>