Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Created January 15, 2019 01:19
Show Gist options
  • Save HaloFour/8c55faef7135355ae31a3ebabf2dd9e3 to your computer and use it in GitHub Desktop.
Save HaloFour/8c55faef7135355ae31a3ebabf2dd9e3 to your computer and use it in GitHub Desktop.
Money Java Async API
public class JMoney {
public static <T, S extends CompletionStage<T>, E extends Exception> S traceAsync(String spanName, CheckedCallable<S, E> callable) throws E {
Tracer tracer = tracer();
tracer.startSpan(spanName);
S stage;
try {
stage = callable.call();
} catch (Exception exception) {
tracer.stopSpan(false);
@SuppressWarnings("unchecked")
E checked = (E) exception;
throw checked;
}
if (stage != null) {
CompletableFuture<T> future = stage.toCompletableFuture();
if (future.isDone()) {
boolean success = !(future.isCompletedExceptionally() || future.isCancelled());
tracer.stopSpan(success);
} else {
Option<Span> span = SpanLocal.pop();
if (span.isDefined()) {
Map<String, String> mdc = MDC.getCopyOfContextMap();
stage.whenComplete((result, exception) -> {
Map<String, String> previous = MDC.getCopyOfContextMap();
if (mdc != null) {
MDC.setContextMap(mdc);
} else {
MDC.clear();
}
SpanLocal.push(span.get());
boolean success = exception == null;
tracer.stopSpan(success);
if (previous != null) {
MDC.setContextMap(previous);
} else {
MDC.clear();
}
});
}
}
} else {
tracer.stopSpan(true);
}
return stage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment