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
Empty file added process/build-test-java17
Empty file.
Empty file added process/build-test-java21
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.IntPredicate;

Expand Down Expand Up @@ -92,6 +93,13 @@ public sealed interface PipelineBuilder<O> permits PipelineBuilder.Error, Pipeli
*/
O run();

/**
* Run the process or pipeline asynchronously.
*
* @return the asynchronous result (not {@code null} but may yield {@code null})
*/
CompletableFuture<O> runAsync();

/**
* Add a failure exit code checker.
* The checker returns {@code true} if the process execution should fail for this exit code.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class PipelineRunner<O> {
private Thread waitForThread;
private ProcessHandlerException exitCheckerProblem;
private AbnormalExitException abnormalExit;
Thread asyncThread;
Process process;
private Gatherer errorGatherer;
private Gatherer outputGatherer;
Expand Down Expand Up @@ -498,6 +499,7 @@ void startThreads() {
errorExtraThreads.forEach(Thread::start);
startThread(whileRunningThread);
startThread(waitForThread);
startThread(asyncThread);
if (prev != null) {
prev.startThreads();
}
Expand Down Expand Up @@ -542,6 +544,7 @@ void unpark() {
errorExtraThreads.forEach(LockSupport::unpark);
LockSupport.unpark(whileRunningThread);
LockSupport.unpark(waitForThread);
LockSupport.unpark(asyncThread);
if (prev != null) {
prev.unpark();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.IntPredicate;

Expand Down Expand Up @@ -189,6 +190,12 @@ public O run() {
return makeRunner().run();
}

public CompletableFuture<O> runAsync() {
check();
locked = true;
return makeRunner().runAsync();
}

private ProcessRunner<O> makeRunner() {
return new ProcessRunner<O>(this, prev == null ? null : prev.makePipelineRunner());
}
Expand Down Expand Up @@ -242,6 +249,10 @@ public O run() throws AbnormalExitException {
return ProcessBuilderImpl.this.run();
}

public CompletableFuture<O> runAsync() {
return ProcessBuilderImpl.this.runAsync();
}

public ProcessBuilder<O> exitCodeChecker(final IntPredicate checker) {
return ProcessBuilderImpl.this.exitCodeChecker(checker);
}
Expand Down
90 changes: 67 additions & 23 deletions process/src/main/java/io/smallrye/common/process/ProcessRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.LockSupport;
Expand Down Expand Up @@ -59,17 +60,42 @@ void taskComplete() {
}
}

O run() {
ThreadFactory tf;
// todo: if (Thread.currentThread().isVirtual()) { ... }
tf = task -> new Thread(() -> {
log.trace("Starting process thread");
try {
task.run();
} finally {
log.trace("Ending process thread");
CompletableFuture<O> runAsync() {
CompletableFuture<O> cf = new CompletableFuture<>();
ThreadFactory tf = threadFactory();
asyncThread = tf.newThread(() -> {
if (awaitOk()) {
Thread shutdownHook = registerHook();
await();
try {
cf.complete(complete());
} catch (Throwable t) {
cf.completeExceptionally(t);
} finally {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
}
});
if (asyncThread == null) {
throw new PipelineExecutionException("Failed to start process thread(s)", noThread(tf));
}
asyncThread.setName("process-async-handler");
initialize(tf);
return cf;
}

O run() {
initialize(threadFactory());
Thread shutdownHook = registerHook();
try {
await();
} finally {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
return complete();
}

private void initialize(final ThreadFactory tf) {
int taskCnt;
try {
// start up input, output, error, and wait-for threads
Expand Down Expand Up @@ -102,8 +128,23 @@ O run() {
}
status = STATUS_STARTED;
unpark();
}

private void await() {
int cnt = taskCount;
if (cnt != 0) {
waiters.add(Thread.currentThread());
}
do {
Thread.interrupted();
LockSupport.park(this);
cnt = taskCount;
} while (cnt != 0);
}

private Thread registerHook() {
Thread shutdownHook = new Thread(() -> {
int cnt = taskCnt;
int cnt = taskCount;
if (cnt != 0) {
waiters.add(Thread.currentThread());
do {
Expand All @@ -116,19 +157,10 @@ O run() {
}
}, "pipeline-shutdown");
Runtime.getRuntime().addShutdownHook(shutdownHook);
try {
int cnt = taskCnt;
if (cnt != 0) {
waiters.add(Thread.currentThread());
}
do {
Thread.interrupted();
LockSupport.park(this);
cnt = taskCount;
} while (cnt != 0);
} finally {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
return shutdownHook;
}

private O complete() {
List<ProcessExecutionException> problems = new ArrayList<>(4);
collectProblems(problems);
return switch (problems.size()) {
Expand All @@ -142,6 +174,18 @@ O run() {
};
}

private static ThreadFactory threadFactory() {
// todo: if (Thread.currentThread().isVirtual()) { ... }
return task -> new Thread(() -> {
log.trace("Starting process thread");
try {
task.run();
} finally {
log.trace("Ending process thread");
}
});
}

boolean awaitOk() {
while (status == STATUS_WAITING) {
LockSupport.park(this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import java.net.URL;
import java.util.ArrayDeque;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;
Expand All @@ -31,6 +33,19 @@ public void testSimpleCat() throws Exception {
assertEquals(strings, result);
}

@Test
public void testSimpleCatAsync() throws Exception {
List<String> strings = List.of("Hello", "world", "foo", "bar");
CompletableFuture<List<String>> future = ProcessBuilder.newBuilder(ProcessUtil.pathOfJava(), findHelper(Cat.class))
.input()
.fromStrings(strings)
.output()
.toStringList(10, 1024)
.runAsync();
List<String> result = future.get();
assertEquals(strings, result);
}

@Test
public void testSimpleCatWithTee() throws Exception {
List<String> strings = List.of("Hello", "world", "foo", "bar");
Expand Down Expand Up @@ -110,6 +125,23 @@ public void testFailure() throws Exception {
}
}

@Test
public void testFailureAsync() throws Throwable {
CompletableFuture<Void> cf = ProcessBuilder.newBuilder(ProcessUtil.pathOfJava(), findHelper(Errorifier.class, "7"))
.runAsync();
try {
try {
cf.get();
fail("Expected specific exception");
} catch (ExecutionException e) {
throw e.getCause();
}
fail("Expected specific exception");
} catch (AbnormalExitException e) {
assertEquals(7, e.exitCode());
}
}

@Test
public void testFailingPipeline() throws Exception {
try {
Expand Down