Skip to content

Commit

Permalink
Using threads to asynchronously read output and error streams before …
Browse files Browse the repository at this point in the history
…waitFor() (#62)
  • Loading branch information
Maninthemire authored Aug 20, 2024
1 parent 873650b commit e90e472
Showing 1 changed file with 40 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

package com.tencent.trpc.codegen.protoc;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -111,15 +113,50 @@ private ProtocExecutionResult runProtoc(ProcessBuilder processBuilder) {
}

private ProtocExecutionResult fetchProcessResult(Process p) {
StringBuilder outputBuilder = new StringBuilder();
StringBuilder errorBuilder = new StringBuilder();

// Using threads to asynchronously read output and error streams.
Thread outputThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
outputBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
log.error("failed to read output stream", e);
}
});

Thread errorThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
errorBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
log.error("failed to read error stream", e);
}
});

outputThread.start();
errorThread.start();

try {
int code = p.waitFor();
outputThread.join();
errorThread.join();

if (code == 0) {
return ProtocExecutionResult.success(IOUtils.toString(p.getInputStream(), StandardCharsets.UTF_8));
return ProtocExecutionResult.success(outputBuilder.toString());
} else {
return ProtocExecutionResult.fail("run protoc failed with exit-code " + code,
IOUtils.toString(p.getErrorStream(), StandardCharsets.UTF_8), null);
errorBuilder.toString(), null);
}
} catch (IOException | InterruptedException e) {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return ProtocExecutionResult.fail("execute protoc failed", null, e);
}
}
Expand Down

0 comments on commit e90e472

Please sign in to comment.