title: Thread Pool per key in Java
body: <p>Suppose that you have a grid <code>G</code> of <code>n x m</code> cells, where <code>n</code> and <code>m</code> are huge. 
  Further, suppose that we have numerous tasks, where each task belong to a single cell in G, and should be executed in parallel (in a thread pool or other resource pool).</p>
  
  <p>However, task belonging to the same cell must be done serially, that is, it should wait that previous task in the same cell to be done.</p>
  
  <p>How can I solve this issue?
  I've search and used several thread pools (Executors, Thread), but no luck.</p>
  
  <p>Minimum Working Example</p>
  
  <pre><code>import java.util.Random;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  
  public class MWE {
  
      public static void main(String[] args) {
          ExecutorService threadPool = Executors.newFixedThreadPool(16);
          Random r = new Random();
  
          for (int i = 0; i &lt; 10000; i++) {
              int nx = r.nextInt(10);
              int ny = r.nextInt(10);
  
              Runnable task = new Runnable() { 
                  public void run() { 
                    try {
                      System.out.println("Task is running"); 
                      Thread.sleep(1000);
                    } catch (InterruptedException e) {
                      e.printStackTrace();
                    }
                  } 
              };
  
              threadPool.submit(new Thread(task)); // Should use nx,ny here somehow
          }
      }
  
  }
  </code></pre>