title: Custom thread pool in Java 8 parallel stream
body: <p>Is it possible to specify a custom thread pool for Java 8 <a href="http://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html">parallel stream</a>? I can not find it anywhere. </p>
  
  <p>Imagine that I have a server application and I would like to use parallel streams. But the application is large and multi-threaded so I want to compartmentalize it. I do not want a slow running task in one module of the applicationblock tasks from another module.</p>
  
  <p>If I can not use different thread pools for different modules, it means I can not safely use parallel streams in most of real world situations.</p>
  
  <p>Try the following example. There are some CPU intensive tasks executed in separate threads.
  The tasks leverage parallel streams. The first task is broken, so each step takes 1 second (simulated by thread sleep). The issue is that other threads get stuck and wait for the broken task to finish. This is contrived example, but imagine a servlet app and someone submitting a long running task to the shared fork join pool. </p>
  
  <pre><code>public class ParallelTest {
      public static void main(String[] args) throws InterruptedException {
          ExecutorService es = Executors.newCachedThreadPool();
  
          es.execute(() -&gt; runTask(1000)); //incorrect task
          es.execute(() -&gt; runTask(0));
          es.execute(() -&gt; runTask(0));
          es.execute(() -&gt; runTask(0));
          es.execute(() -&gt; runTask(0));
          es.execute(() -&gt; runTask(0));
  
  
          es.shutdown();
          es.awaitTermination(60, TimeUnit.SECONDS);
      }
  
      private static void runTask(int delay) {
          range(1, 1_000_000).parallel().filter(ParallelTest::isPrime).peek(i -&gt; Utils.sleep(delay)).max()
                  .ifPresent(max -&gt; System.out.println(Thread.currentThread() + " " + max));
      }
  
      public static boolean isPrime(long n) {
          return n &gt; 1 &amp;&amp; rangeClosed(2, (long) sqrt(n)).noneMatch(divisor -&gt; n % divisor == 0);
      }
  }
  </code></pre>