title: Gmail IMAP, Searching for optimal method for X most recently active Gmail threads
body: <p>I am looking for the optimal way to acquire a list of the top X most recently active Gmail threads.  </p>
  
  <p><strong>Background:</strong></p>
  
  <p>I am using Java accessing <a href="http://code.google.com/apis/gmail/oauth/" rel="nofollow">IMAP with OAuth</a> in a Google Apps for Education domain.  A <a href="http://code.google.com/apis/gmail/docs/inbox_feed.html" rel="nofollow">Gmail Atom inbox feed</a> is available which can list the last 20 threads containing unread messages.  Access to this feed seems to be very fast much faster than anything I having managed to produce using OAuth/IMAP.</p>
  
  <p>The advantage of using the IMAP approach over the Gmail Atom inbox feed is with IMAP I can access an arbitrary number of messages (not just 20), see read messages, get thread size, get any associated google labels, fetch quota details and check for flags.  Essentially this will give my users a much more Gmail like experience (I only need a read only experience for our portal).  My problem is IMAP access is significantly slower than the Atom feed.  Comparison wise the IMAP method takes around 10 seconds whilst the Atom feed is usually returned within 2 seconds.</p>
  
  <p>I am aware and have been working with the <a href="http://code.google.com/apis/gmail/imap/" rel="nofollow">Gmail IMAP Extensions</a> and <a href="http://mail.google.com/support/bin/answer.py?answer=7190" rel="nofollow">Gmail Advanced Search syntax</a> .</p>
  
  <p><strong>Current Method:</strong></p>
  
  <p>Imagine I want the top 40 threads from my IMAP inbox.  Currently I download some arbitrary number of messages say (40 * 4), fetching only the <em>X-GM-THRID</em>.  I iterate through these messages storing the thread id as I go (fetching more messages if required) until I either exhaust the list of inbox messages or I reach my target number of threads.</p>
  
  <p>I then have a list of Gmail thread ids which I can use to perform an IMAP search (with an appropriate FetchProfile.Item's, depending on what message details are required).</p>
  
  <p>I iterate through the search results producing something like (using the wonderful <a href="http://code.google.com/p/guava-libraries/" rel="nofollow">Google Guava/Google Collections</a> Multimap):</p>
  
  <pre><code>Multimap&lt;Long, Message&gt; threadMultiMap = LinkedListMultimap.create();
  </code></pre>
  
  <p>and this is easily massaged into:</p>
  
  <pre><code>LinkedHashMap&lt;Long, Message[]&gt; threadMap; 
  </code></pre>
  
  <p><strong>Is there a better way than iterating through the INBOX until X distinct message threads have been identified?</strong></p>