Java ForkJoinTask completeExceptionally() Method

The completeExceptionally() method of ForkJoinTask class completes this task abnormally, and if not already aborted or canceled, causes it to throw the given exception upon join and related operations.

Syntax

public void completeExceptionally(Throwable ex)

Parameter

ex - the exception to throw.

Returns

Have void as return type.

Throw

No exception is thrown.

Example 1

import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; public class ForkJoinTaskcompleteExceptionallyExample1 { public static void main(String[] args) throws InterruptedException, ExecutionException { ForkJoinPool fpool = new ForkJoinPool(); TaskD3 task1 = new TaskD3(); String rslt = "task Done successfully!!"; ForkJoinTask fpool2 = ForkJoinTask.adapt(task1,rslt); fpool.invoke(fpool2); if(fpool.getPoolSize() < 2) { Exception ex = new Exception(); fpool2.completeExceptionally(ex); System.out.println(" task cancelled ? : "+fpool2.cancel(true)); System.out.println(" task changed ? : " + fpool2.compareAndSetForkJoinTaskTag((short)115,(short)254)); System.out.println(fpool2.isDone()); System.out.println(fpool2.join()); class TaskD3 implements Runnable{ public void run(){ public void call() { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(e); Test it Now

Output:

task cancelled ? : false
 task changed ? : false
task Done successfully!!

Example 2

import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; public class ForkJoinTaskcompleteExceptionallyExample2 { public static void main(String[] args) throws InterruptedException, ExecutionException { ForkJoinPool fpool = new ForkJoinPool(); TaskD2 task1 = new TaskD2(); String rslt = "task Done!!"; ForkJoinTaskfpool2 = ForkJoinTask.adapt(task1,rslt); fpool.invoke(fpool2); if(!fpool.getAsyncMode()) { Exception ex = new Exception(); fpool2.completeExceptionally(ex); System.out.println(" task cancelled ? : "+fpool2.cancel(true)); System.out.println(" task changed ? : " + fpool2.compareAndSetForkJoinTaskTag((short)115,(short)254)); System.out.println(fpool2.isDone()); System.out.println(fpool2.join()); class TaskD2 implements Runnable{ public void run(){ public void call() { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println(e); Test it Now

Output:

task cancelled ? : false
 task changed ? : false
task Done!!
Next TopicJava ForkJoinTask