title: Cancel function in a java ThreadPool - Detect specific runnable in the Pool and cancel it
body: <p>I have a ThreadPool in my android application where I run a bunch of threads in different situation in it.</p>
  
  <pre><code>public class ThreadPoolExecuter {
  
      private final ExecutorService mExecuter;
      private static final int nThreads = 5;
  
      private ThreadPoolExecuter() { 
          this.mExecuter = Executors.newFixedThreadPool(nThreads);
      }
  </code></pre>
  
  <p>Java ThreadPool have no default to cancel thread. One solution that I thought about was keeping a key-value pairs of Future when I submit runnable.</p>
  
  <pre><code>public void add(Runnable runnable) {
      Future&lt;?&gt; future = this.mExecuter.submit(runnable);
      // Add future to my key-value pairs
      if(Constant.DEBUG) Log.d(TAG, "Task submitted.");
  }
  </code></pre>
  
  <p>And then have a cancel function:</p>
  
  <pre><code>public boolean cancel(KEY) {
     Future&lt;?&gt; future = map.get(KEY)
     return future.cancel(mayInterruptIfRunning);
  }
  </code></pre>
  
  <p>Let's say a HashMap. The value is the Future, what about key? 1)What is your suggestion?</p>
  
  <pre><code>Map&lt;Key, Future&lt;?&gt;&gt; map = new HashMap()&lt;key, Future&lt;?&gt;&gt;;
  </code></pre>
  
  <p>About the key I thought about passing an id for every runnable as follows: </p>
  
  <p>2)what do you think about this solution?</p>
  
  <p>But I would mention that in my runnable class sometimes I faced with InterruptedException. Is there any way to avoid it?</p>
  
  <pre><code>class Runner implements Runnable {
  
      private int id;
  
      public Runner(int id) {
          this.id = id;
      }
  
      @Override
      public void run() {
  
          System.out.println("Starting " + id);
          try {
              Thread.sleep(100);
          } catch (InterruptedException e) {
              System.out.println("Crashed on:" + Thread.currentThread().getId());
          }
          System.out.println("ending " + id);
      }
  }
  </code></pre>
  
  <p>3 ) At the end I want to add it is important for me to know any better solution in your point of view to develop a cancel function in java ThreadPool?</p>
  
  <p>Notice that I don't look for a replacement for my ThreadPool such as AsyncTask in Android which has default cancellation.</p>