title: Android multithreading job executor based on queue contents
body: <p>I am developing an android application and in the application i am performing a lot of background tasks. The requirement is that all the requests should be processed serially and can be executed in parallel. 
  Ex: Assume that i am getting task requests one after the other. To add these tasks i am maintaining a request Queue. Let's say the current queue status is</p>
  
  <p>(Head) Task1 -> Task2 - Task3 - Task4 -Task5 - Task6 (Tail)</p>
  
  <p>I am having a thread pool which executes the tasks in parallel. Executor always picks the task at head and submits to thread pool to execute. 
  In my requirement, sometimes i need to remove the tasks from the queue which are no more required. And the design is such that old tasks are removed which are no more required. Let's say Task1 and Task2 are being executed by the threadpool while remaining tasks are waiting in queue. The current queue state is </p>
  
  <p>(Head) Task3 - Task4 -Task5 - Task6 (Tail)</p>
  
  <p>Assume a call is made to remove old tasks i.e Task3 and Task4. These tasks should be removed and Task4 is submitted as next task for the thread pool.</p>
  
  <p>What i need:
  I need a job manager to manage these operations like
  1. Check for request queue continuously and dispatch tasks to thread pool
  2. Whenever removeTask is called, remove tasks and then continue dispatch of events from the queue until the queue becomes empty
  3. If the queue becomes empty, the thread needs to wait/sleep until the next request comes to queue.
  4. The job manager should monitor and pick tasks in the queue and execute in executor service, go to wait state or sleep state when the queue is empty and wake up to execute tasks when there are items in queue and continue..
  5. (Important) I want UI thread to be given preference in accessing request queue.  </p>
  
  <p>What i have:
  1. An atomic reference of request queue shared by UI thread and job Manager(another backround thread)
  2. Ready tasks</p>
  
  <p>I thought of using </p>
  
  <pre><code>while(true) {    
  //check for any items in the queue and execute
  }
  </code></pre>
  
  <p>in job manager run() method but that unnecessarily consumes CPU when the queue is empty</p>
  
  <p>Please provide me logic for jobManager.</p>
  
  <p>Also one more questionn. Does creating atomic reference of request queue ensures thread safety ? or should i make the request queue variable synchronized ?</p>