Future State Non Blocking Polling

Read a Future's terminal state non-blockingly with state() and the State enum, distinguishing SUCCESS, FAILED, CANCELLED, and RUNNING without waiting.

JavaResilience

Code

snippet
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureStatePoll {

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        try {
            Future<String> ok = pool.submit(() -> "done");
            Future<String> failed = pool.submit(() -> {
                throw new IllegalStateException("bad job");
            });
            Future<String> pending = pool.submit(() -> {
                Thread.sleep(10_000);
                return "late";
            });

            // state() reads the terminal state without blocking; get() first removes races
            System.out.println("ok      -> " + ok.get() + " " + ok.state());

            try {
                failed.get();
            } catch (ExecutionException boom) {
                // FAILED 终态:cause 是任务里抛出的原始异常
                System.out.println("failed  -> " + failed.state()
                        + " cause " + boom.getCause().getMessage());
            }

            // state() 不阻塞:仍在跑的任务显示 RUNNING,与 get() 不同
            System.out.println("pending -> " + pending.state());

            pending.cancel(true);
            System.out.println("cancelled -> " + pending.state());
        } finally {
            pool.shutdownNow();
        }
    }
}

What the code does

Future State Non Blocking Polling reduces to the class FutureStatePoll.

The IllegalStateException throw sits inside a try: execution reaches it unconditionally, and the surrounding handler catches it.

Applying it

The demo output is labeled (ok ->, failed ->, pending ->), so every printed line maps back to its originating operation.

Statements that matter

ExecutorService pool = Executors.newFixedThreadPool(2);
throw new IllegalStateException("bad job");
Thread.sleep(10_000);

Interactive Tools for This Topic

FAQ

Does the snippet validate its input?
No — the `IllegalStateException` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
What does Future State Non Blocking Polling print when run?
Invoke the file as-is — the `ok ->`, `failed ->`, `pending ->` prefixes identify which step printed each line.