Created
June 18, 2022 01:15
-
-
Save jyemin/7fb6e495843ff2405e465280faa6abe4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mongodb.client; | |
import java.time.Duration; | |
import java.util.Optional; | |
public class TimeoutScope implements AutoCloseable { | |
private static final ThreadLocal<TimeoutScope> THREAD_LOCAL_TIMEOUT_SCOPE = new ThreadLocal<>(); | |
public static TimeoutScope withDuration(final Duration duration) { | |
if (THREAD_LOCAL_TIMEOUT_SCOPE.get() != null) { | |
throw new IllegalStateException("Not supported yet"); // TODO: support nested timeout scopes | |
} | |
TimeoutScope timeoutScope = new TimeoutScope(duration); | |
THREAD_LOCAL_TIMEOUT_SCOPE.set(timeoutScope); | |
return timeoutScope; | |
} | |
public static Optional<TimeoutScope> current() { | |
return Optional.ofNullable(THREAD_LOCAL_TIMEOUT_SCOPE.get()); | |
} | |
private final long startTime = System.nanoTime(); | |
private final Duration duration; | |
private TimeoutScope(final Duration duration) { | |
this.duration = duration; | |
} | |
public long getStartTime() { | |
return startTime; | |
} | |
private Duration getDuration() { | |
return duration; | |
} | |
/** | |
* May be negative | |
* | |
* @return the remaining duration on the timeout, which may be negative | |
*/ | |
public Duration remaining() { | |
return duration.minus(Duration.ofNanos(System.nanoTime() - startTime)); | |
} | |
@Override | |
public void close() throws Exception { | |
THREAD_LOCAL_TIMEOUT_SCOPE.remove(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment