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