Created
February 20, 2015 21:25
-
-
Save jkubrynski/dc8008c6d44af25c2d25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
Happy hAkking!