Created
December 19, 2022 05:46
-
-
Save sha1n/8505d95959ecc377d35bc25b12ab4443 to your computer and use it in GitHub Desktop.
ForkJoin use and abuse examples
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
package com.example; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ForkJoinPool; | |
import java.util.concurrent.ForkJoinTask; | |
public class ForkJoinUseAndAbuseExample { | |
public static void main(String[] args) throws InterruptedException, ExecutionException { | |
ForkJoinPool fgp = new ForkJoinPool(1); | |
/* | |
* Example of ForkJoinPool abuse. In this example ForkJoinPool is used as an Executor and although constructed | |
* with parallelism=1, it will create 4 threads to complete this nested task! | |
*/ | |
System.out.printf("Example 1 returned: %d\n\n", | |
CompletableFuture.supplyAsync(() -> { | |
System.out.printf("1: %s\n", Thread.currentThread().getName()); | |
return CompletableFuture.supplyAsync(() -> { | |
System.out.printf("2: %s\n", Thread.currentThread().getName()); | |
return CompletableFuture.supplyAsync(() -> { | |
System.out.printf("3: %s\n", Thread.currentThread().getName()); | |
return CompletableFuture.supplyAsync(() -> { | |
System.out.printf("4: %s\n", Thread.currentThread().getName()); | |
return 1; | |
}, fgp).join(); | |
}, fgp).join(); | |
}, fgp).join(); | |
}, fgp).join() | |
); | |
/* | |
* Example of a nested ForkJoinTask that allegedly require 4 threads to complete, but successfully completes | |
* with only a single thread thanks to the ForkJoinPool task management capabilities. | |
* This example takes full advantage of the fork-join framework and is able to use resources more effectively. | |
*/ | |
System.out.printf("Example 2 returned: %d\n\n", | |
fgp.invoke(ForkJoinTask.adapt(() -> { | |
System.out.printf("1: %s\n", Thread.currentThread().getName()); | |
return ForkJoinTask.adapt(() -> { | |
System.out.printf("2: %s\n", Thread.currentThread().getName()); | |
return ForkJoinTask.adapt(() -> { | |
System.out.printf("3: %s\n", Thread.currentThread().getName()); | |
return ForkJoinTask.adapt(() -> { | |
System.out.printf("4: %s\n", Thread.currentThread().getName()); | |
return 1; | |
}).fork().get(); | |
}).fork().get(); | |
}).fork().get(); | |
})) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment