Add unit test for asynchronous browse

This commit is contained in:
Rene Pfeuffer
2019-12-11 13:32:05 +01:00
parent 7c0eb9251a
commit 093c0abb02
2 changed files with 96 additions and 0 deletions

View File

@@ -1,7 +1,12 @@
package sonia.scm.repository.spi;
import java.io.Closeable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.function.Consumer;
import static sonia.scm.repository.spi.SyncAsyncExecutor.ExecutionType.ASYNCHRONOUS;
import static sonia.scm.repository.spi.SyncAsyncExecutor.ExecutionType.SYNCHRONOUS;
public final class SyncAsyncExecutors {
@@ -20,4 +25,70 @@ public final class SyncAsyncExecutors {
}
};
}
public static SyncAsyncExecutor asynchronousExecutor() {
Executor executor = Executors.newSingleThreadExecutor();
return new SyncAsyncExecutor() {
@Override
public ExecutionType execute(Consumer<ExecutionType> runnable) {
executor.execute(() -> runnable.accept(ASYNCHRONOUS));
return ASYNCHRONOUS;
}
@Override
public boolean hasExecutedAllSynchronously() {
return true;
}
};
}
public static AsyncExecutorStepper stepperAsynchronousExecutor() {
Executor executor = Executors.newSingleThreadExecutor();
Semaphore enterSemaphore = new Semaphore(0);
Semaphore exitSemaphore = new Semaphore(0);
return new AsyncExecutorStepper() {
@Override
public void close() {
enterSemaphore.release(Integer.MAX_VALUE);
exitSemaphore.release(Integer.MAX_VALUE);
}
@Override
public ExecutionType execute(Consumer<ExecutionType> runnable) {
executor.execute(() -> {
try {
enterSemaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
runnable.accept(ASYNCHRONOUS);
exitSemaphore.release();
});
return ASYNCHRONOUS;
}
@Override
public void next() {
enterSemaphore.release();
try {
exitSemaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public boolean hasExecutedAllSynchronously() {
return true;
}
};
}
public interface AsyncExecutorStepper extends SyncAsyncExecutor, Closeable {
void next();
}
}