Skip to content

Instantly share code, notes, and snippets.

@bergman
Created February 8, 2018 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bergman/051bca371b9d8f1ae0015443d6c3f9ca to your computer and use it in GitHub Desktop.
Save bergman/051bca371b9d8f1ae0015443d6c3f9ca to your computer and use it in GitHub Desktop.
decisions
public static class Result<T> implements Future<T> {
private Future<T> future;
private Result(Future<T> future) {
this.future = future;
}
/**
* Block until done and {@code System.exit()} with an appropriate status code.
*/
public void blockAndExit() {
blockAndExit(System::exit);
}
void blockAndExit(Consumer<Integer> exiter) {
try {
future.get();
exiter.accept(0);
} catch (ExecutionException e) {
final int status;
if (e.getCause() instanceof NotReady) {
status = 20;
} else if (e.getCause() instanceof Persisted) {
status = 0;
} else {
status = 1;
}
exiter.accept(status);
} catch (RuntimeException | InterruptedException e) {
exiter.accept(1);
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return future.isCancelled();
}
@Override
public boolean isDone() {
return future.isDone();
}
@Override
public T get() throws InterruptedException, ExecutionException {
return future.get();
}
@Override
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return future.get(timeout, unit);
}
}
public static class Result<T> implements Future<T> {
private Future<T> future;
private Result(Future<T> future) {
this.future = future;
}
public Future<T> future() {
return future;
}
/**
* Block until done and {@code System.exit()} with an appropriate status code.
*/
public void blockAndExit() {
blockAndExit(System::exit);
}
void blockAndExit(Consumer<Integer> exiter) {
try {
future.get();
exiter.accept(0);
} catch (ExecutionException e) {
final int status;
if (e.getCause() instanceof NotReady) {
status = 20;
} else if (e.getCause() instanceof Persisted) {
status = 0;
} else {
status = 1;
}
exiter.accept(status);
} catch (RuntimeException | InterruptedException e) {
exiter.accept(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment