Bygdøy during winter

Future<T>

public String downloadContents(URL url) throws IOException { try(InputStream input = url.openStream()) { return IOUtils.toString(input, StandardCharsets.UTF_8); } } //... final String contents = downloadContents(new URL("http://www.example.com"));

downloadContents()

Thread

wait()

notify()

Future<T>

public static Future<String> startDownloading(URL url) { //... } final Future<String> contentsFuture = startDownloading(new URL("http://www.example.com")); //other computation final String contents = contentsFuture.get();

startDownloading()

startDownloading()

Future<String>

String

Future.get()

Future

Future

String

get()

TimeoutException

Future

final Future<String> contentsFuture = startDownloading(new URL("http://www.example.com")); while (!contentsFuture.isDone()) { askUserToWait(); doSomeComputationInTheMeantime(); } contentsFuture.get();

contentsFuture.get()

Future.isDone()

true

isDone()

contentsFuture.cancel(true); //meh...

false

mayInterruptIfRunning

Future

Callable.call()

true

Future.cancel()

Object.wait()

Callable

InterruptedException

Future<T>

Future<T>

startDownloading()

private final ExecutorService pool = Executors.newFixedThreadPool(10); public Future<String> startDownloading(final URL url) throws IOException { return pool.submit(new Callable<String>() { @Override public String call() throws Exception { try (InputStream input = url.openStream()) { return IOUtils.toString(input, StandardCharsets.UTF_8); } } }); }

Callable<String>

submit()

Future<String>

cancel()

Future

@Async public Future<String> startDownloading(final URL url) throws IOException { try (InputStream input = url.openStream()) { return new AsyncResult<>( IOUtils.toString(input, StandardCharsets.UTF_8) ); } }

Future

startDownloading()

java.util.concurrent.Future