Java : FutureTask with Examples

FutureTask (Java SE 18 & JDK 18) API Examples.
You will find code examples on most FutureTask methods.


Summary

A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed.

Class diagram

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        System.out.println("task run");
    }, "abcd");

    executorService.submit(futureTask);

    System.out.println("get : " + futureTask.get());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task run
//get : abcd
//term : true

Constructors

FutureTask (Runnable runnable, V result)

Creates a FutureTask that will, upon running, execute the given Runnable, and arrange that get will return the given result on successful completion.

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        System.out.println("task run");
    }, "abcd");

    executorService.submit(futureTask);

    System.out.println("get : " + futureTask.get());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task run
//get : abcd
//term : true

FutureTask (Callable<V> callable)

Creates a FutureTask that will, upon running, execute the given Callable.

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        System.out.println("task run");
        return "abcd";
    });

    executorService.submit(futureTask);

    System.out.println("get : " + futureTask.get());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task run
//get : abcd
//term : true

Methods

boolean cancel (boolean mayInterruptIfRunning)

Attempts to cancel execution of this task.

final long current = System.nanoTime();
final DoubleSupplier getTime = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start : " + getTime.getAsDouble() + " sec.");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end : " + getTime.getAsDouble() + " sec.");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    // mayInterruptIfRunning = false
    final var ret = futureTask.cancel(false);
    System.out.println("cancel = " + ret + " : " + getTime.getAsDouble() + " sec.");

} finally {
    executorService.shutdown();
    System.out.println("shutdown : " + getTime.getAsDouble() + " sec.");
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term = " + ret + " : " + getTime.getAsDouble() + " sec.");

// Result
// ↓
//task start : 0.0030879 sec.
//cancel = true : 1.0165037 sec.
//shutdown : 1.0204428 sec.
//task end : 2.0135346 sec.
//term = true : 2.0140798 sec.
final long current = System.nanoTime();
final DoubleSupplier getTime = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start : " + getTime.getAsDouble() + " sec.");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end : " + getTime.getAsDouble() + " sec.");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    // mayInterruptIfRunning = true
    final var ret = futureTask.cancel(true);
    System.out.println("cancel = " + ret + " : " + getTime.getAsDouble() + " sec.");

} finally {
    executorService.shutdown();
    System.out.println("shutdown : " + getTime.getAsDouble() + " sec.");
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term = " + ret + " : " + getTime.getAsDouble() + " sec.");

// Result
// ↓
//task start : 0.0035929 sec.
//Interrupted!
//task end : 1.0059904 sec.
//cancel = true : 1.005947 sec.
//shutdown : 1.0097252 sec.
//term = true : 1.0098963 sec.
final long current = System.nanoTime();
final DoubleSupplier getTime = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start : " + getTime.getAsDouble() + " sec.");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end : " + getTime.getAsDouble() + " sec.");
        }
    });

    executorService.submit(futureTask);

    // Wait for the task to complete.
    TimeUnit.SECONDS.sleep(3);

    final var ret = futureTask.cancel(true);
    System.out.println("cancel = " + ret + " : " + getTime.getAsDouble() + " sec.");

} finally {
    executorService.shutdown();
    System.out.println("shutdown : " + getTime.getAsDouble() + " sec.");
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term = " + ret + " : " + getTime.getAsDouble() + " sec.");

// Result
// ↓
//task start : 0.0022581 sec.
//task end : 2.0066302 sec.
//cancel = false : 3.0161829 sec.
//shutdown : 3.0202056 sec.
//term = true : 3.0203844 sec.

protected void done ()

Protected method invoked when this task transitions to state isDone (whether normally or via cancellation).

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("-- task start --");
            System.out.println("task thread id : " + Thread.currentThread().getId());

            TimeUnit.SECONDS.sleep(1);
            return "abcd";

        } finally {
            System.out.println("-- task end --");
        }
    }) {
        @Override
        protected void done() {
            System.out.println("done!");
            System.out.println("done thread id : " + Thread.currentThread().getId());
        }
    };

    System.out.println("main thread id : " + Thread.currentThread().getId());
    executorService.submit(futureTask);

    System.out.println("get : " + futureTask.get());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//main thread id : 1
//-- task start --
//task thread id : 19
//-- task end --
//done!
//get : abcd
//done thread id : 19
//term : true
final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("-- task start --");
            System.out.println("task thread id : " + Thread.currentThread().getId());

            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } finally {
            System.out.println("-- task end --");
        }
    }) {
        @Override
        protected void done() {
            System.out.println("done!");
            System.out.println("done thread id : " + Thread.currentThread().getId());
        }
    };

    System.out.println("main thread id : " + Thread.currentThread().getId());
    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    futureTask.cancel(true);
    System.out.println("isCancelled : " + futureTask.isCancelled());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//main thread id : 1
//-- task start --
//task thread id : 19
//-- task end --
//done!
//done thread id : 1
//isCancelled : true
//term : true

V get ()

Waits if necessary for the computation to complete, and then retrieves its result.

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- get start --");

    final var ret = futureTask.get();

    System.out.println("-- get end --");
    System.out.println("future ret : " + ret);

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- get start --
//task end
//-- get end --
//future ret : abcd
//term : true
final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);

            throw new IllegalStateException("Exception!");

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- get start --");

    final var ret = futureTask.get();

    System.out.println("-- get end --");
    System.out.println("future ret : " + ret);

} catch (ExecutionException e) {
    System.out.println("ExecutionException! : " + e.getMessage());
} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- get start --
//task end
//ExecutionException! : java.lang.IllegalStateException: Exception!
//term : true
final var executorService = Executors.newScheduledThreadPool(2);
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(3);

            return "abcd";

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    executorService.schedule(() -> {
        System.out.println("future cancel");
        futureTask.cancel(true);
    }, 2, TimeUnit.SECONDS);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- get start --");

    final var ret = futureTask.get();

    System.out.println("-- get end --");
    System.out.println("future ret : " + ret);

} catch (CancellationException e) {
    System.out.println("CancellationException!");
} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- get start --
//future cancel
//Interrupted!
//task end
//CancellationException!
//term : true

V get (long timeout, TimeUnit unit)

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(3);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- get start --");

    final var ret = futureTask.get(5, TimeUnit.SECONDS);

    System.out.println("-- get end --");
    System.out.println("future ret : " + ret);

} catch (TimeoutException e) {
    System.out.println("TimeoutException!");
} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- get start --
//task end
//-- get end --
//future ret : abcd
//term : true
final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(3);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- get start --");

    final var ret = futureTask.get(1, TimeUnit.SECONDS);

    System.out.println("-- get end --");
    System.out.println("future ret : " + ret);

} catch (TimeoutException e) {
    System.out.println("TimeoutException!");
} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- get start --
//TimeoutException!
//task end
//term : true

boolean isCancelled ()

Returns true if this task was cancelled before it completed normally.

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- before cancel -- : " + futureTask.isCancelled());

    futureTask.cancel(false);

    System.out.println("-- after cancel -- : " + futureTask.isCancelled());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- before cancel -- : false
//-- after cancel -- : true
//task end
//term : true
final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- before cancel -- : " + futureTask.isCancelled());

    // Wait for the task to complete.
    TimeUnit.SECONDS.sleep(2);

    futureTask.cancel(false);

    System.out.println("-- after cancel -- : " + futureTask.isCancelled());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- before cancel -- : false
//task end
//-- after cancel -- : false
//term : true

boolean isDone ()

Returns true if this task completed.

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- isDone 1 -- : " + futureTask.isDone());

    // Wait for the task to complete.
    TimeUnit.SECONDS.sleep(2);

    System.out.println("-- isDone 2 -- : " + futureTask.isDone());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- isDone 1 -- : false
//task end
//-- isDone 2 -- : true
//term : true
final var executorService = Executors.newSingleThreadExecutor();
try {
    final var futureTask = new FutureTask<>(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    });

    executorService.submit(futureTask);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- isDone 1 -- : " + futureTask.isDone());

    futureTask.cancel(false);

    System.out.println("-- isDone 2 -- : " + futureTask.isDone());

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//-- isDone 1 -- : false
//-- isDone 2 -- : true
//task end
//term : true

void run ()

Sets this Future to the result of its computation unless it has been cancelled.

final var futureTask = new FutureTask<>(() -> {
    System.out.println("Run!");
    return "abcd";
});

futureTask.run();

System.out.println("isDone : " + futureTask.isDone());

final var ret = futureTask.get();
System.out.println("get ret : " + ret);

// Result
// ↓
//Run!
//isDone : true
//get ret : abcd

protected boolean runAndReset ()

Executes the computation without setting its result, and then resets this future to initial state, failing to do so if the computation encounters an exception or is cancelled.

final var runnable = new Runnable() {
    private int count;

    @Override
    public void run() {
        count++;
        System.out.println("count : " + count);
    }
};

final var task = new FutureTask<>(runnable, "abcd") {
    @Override
    public void run() {
        final var ret = runAndReset();
        System.out.println("runAndReset ret : " + ret);
    }
};

task.run();
System.out.println("isDone : " + task.isDone());

task.run();
System.out.println("isDone : " + task.isDone());

task.run();
System.out.println("isDone : " + task.isDone());

// Result
// ↓
//count : 1
//runAndReset ret : true
//isDone : false
//count : 2
//runAndReset ret : true
//isDone : false
//count : 3
//runAndReset ret : true
//isDone : false
final var task = new FutureTask<>(() -> {
    throw new IllegalStateException("Exception!");
}) {
    @Override
    public void run() {
        final var ret = runAndReset();
        System.out.println("runAndReset ret : " + ret);
    }
};

task.run();
System.out.println("isDone : " + task.isDone());

// Result
// ↓
//runAndReset ret : false
//isDone : true

protected void set (V v)

Sets the result of this future to the given value unless this future has already been set or has been cancelled.

final var futureTask = new FutureTask<>(() -> {
    try {
        System.out.println("task start");
        return "abcd";
    } finally {
        System.out.println("task end");
    }
}) {
    @Override
    protected void set(String s) {
        super.set(s);
        System.out.println("set : " + s);
    }
};

futureTask.run();

System.out.println("isDone : " + futureTask.isDone());

// Result
// ↓
//task start
//task end
//set : abcd
//isDone : true

protected void setException (Throwable t)

Causes this future to report an ExecutionException with the given throwable as its cause, unless this future has already been set or has been cancelled.

final var futureTask = new FutureTask<>(() -> {
    try {
        System.out.println("task start");
        throw new IllegalStateException("Exception!");
    } finally {
        System.out.println("task end");
    }
}) {
    @Override
    protected void setException(Throwable t) {
        super.setException(t);
        System.out.println("setException : " + t);
    }
};

futureTask.run();

System.out.println("isDone : " + futureTask.isDone());

// Result
// ↓
//task start
//task end
//setException : java.lang.IllegalStateException: Exception!
//isDone : true

String toString ()

Returns a string representation of this FutureTask.

final var futureTask = new FutureTask<>(() -> "abcd");

final var ret1 = futureTask.toString();
System.out.println("before run : " + ret1);

futureTask.run();

final var ret2 = futureTask.toString();
System.out.println("after run : " + ret2);

// Result
// ↓
//before run : java.util.concurrent.FutureTask@c05fddc[Not completed, task = ...]
//after run : java.util.concurrent.FutureTask@c05fddc[Completed normally]

Related posts

To top of page