Skip to content

Instantly share code, notes, and snippets.

@jkubrynski
Created February 20, 2015 21:25
Show Gist options
  • Save jkubrynski/dc8008c6d44af25c2d25 to your computer and use it in GitHub Desktop.
Save jkubrynski/dc8008c6d44af25c2d25 to your computer and use it in GitHub Desktop.
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.concurrent.ForkJoinPool;
/**
* @author Jakub Kubrynski
*/
public class ReplaceCommonPool {
public static void main(String[] args) throws Exception {
System.out.println(ForkJoinPool.commonPool().getParallelism());
replacePool(new ForkJoinPool(1));
System.out.println(ForkJoinPool.commonPool().getParallelism());
}
private static void replacePool(ForkJoinPool newPool) throws ReflectiveOperationException {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
Field common = ForkJoinPool.class.getDeclaredField("common");
long commonOffset = unsafe.staticFieldOffset(common);
unsafe.putObject(ForkJoinPool.class, commonOffset, newPool);
}
}
@ktoso
Copy link

ktoso commented Feb 20, 2015

Hello Kuba,
that's not really the best way of doing this in runtime.

Because of how ForkJoinPool works in Java 8, if you submit a tasks to a FJP from within an existing ForkJoinPool, it's ForkJoinTasks will be submitted to the existing "enclosing" pool, instead of the global one. See ForkJoinTask#fork to read up on the details (inForkJoinPool() is used).

Here's how to do this:

final ForkJoinPool pool = ???
final List<Integer> myList = ???
pool.submit(() -> myList.parallel().filter(i -> i % 2 == 0).collect(toList())).get();

Happy hAkking!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment