~/ learn/ comp-348/ cards/ Thread pools: `ExecutorService`, `Callable`, `Future`
1 of 5

Submit a Callable, hold the Future

Submit a Callable, hold the Future

Answer

ExecutorService pool = Executors.newFixedThreadPool(THREADS); Future<String> f = pool.submit(() -> InetAddress.getByName(host).getHostName()); // ... submit the rest of the work here, before collecting anything ... System.out.println(f.get()); // blocks only if this task is not done yet

The lambda compiles to a `Callable<String>` rather than a `Runnable` because it returns a value and throws a checked `UnknownHostException` — both illegal in `run()`. That single difference is why network tasks want `Callable`.

Harold 4e ch3 §Thread Pools and Executors

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/87367ef5-167a-4b32-9a7f-a149b0435ca6/flashcard utf-8 LF