package com.github.ferstl.streams;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.streams.ParallelStreamSupport;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.Assert.assertThat;


public class ParallelStreamSupportTest {

  private static final Pattern FORK_JOIN_THREAD_NAME_PATTERN = Pattern.compile("ForkJoinPool-\\d+-worker-\\d+");

  private ForkJoinPool workerPool;

  @Before
  public void before() {
    this.workerPool = new ForkJoinPool(1);
  }

  @After
  public void after() throws InterruptedException {
    this.workerPool.shutdown();
    this.workerPool.awaitTermination(1, TimeUnit.SECONDS);
  }

  /**
   * Verify that we use the correct thread name pattern.
   */
  @Test
  public void testForkJoinPoolThreadNamePattern() {
    ForkJoinTask<String> task = ForkJoinTask.adapt(() -> Thread.currentThread().getName());
    String threadName = this.workerPool.invoke(task);

    assertThat(threadName, matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN));
  }

  @Test
  public void collectParallel() {
    List<String> result = ParallelStreamSupport.parallelStream(singletonList("a"), this.workerPool)
        .map(e -> Thread.currentThread().getName())
        .collect(toList());

    assertThat(result, contains(matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN)));
  }

}

@@ -130,20 +130,28 @@
 ForkJoin
-Task
+WorkerThread
 ;%0Aimport
@@ -297,55 +297,45 @@
 ort 
-com.github.ferstl.streams.ParallelStreamSupport
+static java.lang.Thread.currentThread
 ;%0Aim
@@ -527,24 +527,68 @@
 hesPattern;%0A
+import static org.junit.Assert.assertFalse;%0A
 import stati
@@ -843,24 +843,169 @@
  before() %7B%0A
+    // Precondition for all tests%0A    assertFalse(%22This test must not run in a ForkJoinPool%22, currentThread() instanceof ForkJoinWorkerThread);%0A%0A
     this.wor
@@ -1201,363 +1201,8 @@
  %7D%0A%0A
-  /**%0A   * Verify that we use the correct thread name pattern.%0A   */%0A  @Test%0A  public void testForkJoinPoolThreadNamePattern() %7B%0A    ForkJoinTask%3CString%3E task = ForkJoinTask.adapt(() -%3E Thread.currentThread().getName());%0A    String threadName = this.workerPool.invoke(task);%0A%0A    assertThat(threadName, matchesPattern(FORK_JOIN_THREAD_NAME_PATTERN));%0A  %7D%0A
 %0A  @
@@ -1502,15 +1502,14 @@
 ERN)));%0A
+
   %7D%0A
-%0A
 %7D%0A

Add check that this test does not run in a ForkJoinPool