Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,29 @@ public boolean isTerminated() {
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
// FIXME no idea how to passively wait, not really applicable in Rx
long totalTime = unit.convert(timeout, TimeUnit.MILLISECONDS);
long timeoutNanos = unit.toNanos(timeout);
if (isTerminated()) {
return true;
}
if (timeoutNanos <= 0) {
return false;
}

long start = System.nanoTime();
for (;;) {
if (isTerminated()) {
return true;
}

long elapsed = System.nanoTime() - start;
long remaining = timeoutNanos - elapsed;
if (remaining <= 0) {
return isTerminated();
}

while (!isTerminated() && totalTime > 0) {
totalTime--;
Thread.sleep(1);
// There is no termination signal to await, so poll at a short interval.
TimeUnit.NANOSECONDS.sleep(Math.min(remaining, TimeUnit.MILLISECONDS.toNanos(1)));
}
return totalTime > 0;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,4 +216,32 @@ public void invokeAllTimeoutDoesTimeout() throws Throwable {
assertTrue(f.isCancelled(), "Task was not cancelled: " + f);
}
}

@Test
public void awaitTerminationUsesRequestedTimeUnit() throws Exception {
Scheduler scheduler = Schedulers.computation();
Scheduler.Worker worker = scheduler.createWorker();
SchedulerToExecutorService executor = new SchedulerToExecutorService(
scheduler, new AtomicReference<>(worker));

try {
scheduler.scheduleDirect(worker::dispose, 50, TimeUnit.MILLISECONDS);

assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
} finally {
worker.dispose();
}
}

@Test
public void awaitTerminationReturnsTrueIfAlreadyTerminated() throws Exception {
SchedulerToExecutorService executor = new SchedulerToExecutorService(
Schedulers.computation(), new AtomicReference<>(null));

assertFalse(executor.awaitTermination(0, TimeUnit.MILLISECONDS));

executor.shutdown();

assertTrue(executor.awaitTermination(0, TimeUnit.MILLISECONDS));
}
}