FutureTask Turns A Callable Into Shared Result

Wrap a Callable in FutureTask so the expensive work runs exactly once even when several threads block on get, and later callers reuse the cached result.

JavaResilience

Code

javasnippet
35 lines
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class ConfigLoader {

    public static void main(String[] args) throws Exception {
        Callable<String> load = () -> {
            System.out.println("loading config from disk (once)");
            Thread.sleep(50);
            return "db=prod;retries=3";
        };

        // FutureTask turns a one-shot Callable into a shareable result
        FutureTask<String> task = new FutureTask<>(load);

        Thread runner = new Thread(task, "runner");
        Thread consumer = new Thread(() -> {
            try {
                // runner 跑完之前,get() 会一直阻塞
                System.out.println("consumer sees: " + task.get());
            } catch (Exception e) {
                System.out.println("consumer failed: " + e.getMessage());
            }
        }, "consumer");

        runner.start();
        consumer.start();
        runner.join();
        consumer.join();

        // 计算已完成:再调 get() 立即返回缓存结果,不会重新执行
        System.out.println("cached result: " + task.get());
        System.out.println("isDone: " + task.isDone());
    }
}

How it works

The working surface is the class ConfigLoader — everything else is wiring.

Points of care

  • Nothing is assumed beyond the language toolchain itself.

Applying it

The output is tagged as it lands — loading config from disk (once), consumer sees:, consumer failed: — when the file runs.

Statements that matter

Thread runner = new Thread(task, "runner");
Thread consumer = new Thread(() -> {
try {
// runner 跑完之前,get() 会一直阻塞
System.out.println("consumer sees: " + task.get());
} catch (Exception e) {
System.out.println("consumer failed: " + e.getMessage());
}
}, "consumer");
return "db=prod;retries=3";

Interactive Tools for This Topic

FAQ

What does FutureTask Turns A Callable Into Shared Result print when run?
Run it as a complete program — the output lines carry labels such as `loading config from disk (once)`, `consumer sees:`, `consumer failed:`.