title: Simple Thread Management - Java - Android
body: <p>I have an application which spawns a new thread when a user asks for an image to be filtered.</p>
  
  <p>This is the only type of task that I have and all are of equal importance.</p>
  
  <p>If I ask for too many concurrent threads (Max I ever want is 9) the thread manager throws a <strong>RejectedExecutionException</strong>. </p>
  
  <p>At the minute what I do is;</p>
  
  <pre><code>// Manage Concurrent Tasks
  private Queue&lt;AsyncTask&lt;Bitmap,Integer,Integer&gt;&gt; tasks = new LinkedList&lt;AsyncTask&lt;Bitmap,Integer,Integer&gt;&gt;();
  
  @Override
  public int remainingSize() {
      return tasks.size();
  }
  
  @Override
  public void addTask(AsyncTask&lt;Bitmap, Integer, Integer&gt; task) {
      try{
          task.execute(currentThumbnail);
          while(!tasks.isEmpty()){
              task = tasks.remove();
              task.execute(currentThumbnail);
          }
      } catch (RejectedExecutionException r){
          Log.i(TAG,"Caught RejectedExecutionException Exception - Adding task to Queue");
          tasks.add(task);
      }
  }
  </code></pre>
  
  <p>Simply add the rejected task to a queue and the next time a thread is started the queue is checked to see if there is a backlog.</p>
  
  <p>The obvious issue with this is that if the final task gets rejected on its first attempt it will never be restarted (Until after it's no longer needed).</p>
  
  <p>Just wondering if there's a simple model I should use for managing this sort of thing. I need tasks to notify the queue when they are done.</p>