[BUG] Invoking claude from Java process hangs

Resolved 💬 2 comments Opened Apr 22, 2025 by zhangzhang Closed Apr 22, 2025

Environment

  • Platform (select one):
  • [x] Anthropic API
  • [ ] AWS Bedrock
  • [ ] Google Vertex AI
  • [ ] Other: <!-- specify -->
  • Claude CLI version: 0.2.72 (Claude Code)
  • Operating System: macOS 15.4.1
  • Terminal: N/A

Bug Description

While trying to invoke the Claude code from a Java process, the program hangs while waiting for output.

Steps to Reproduce

  1. Example Code:

public static void main(String[] args) {
try {
System.out.println( System.getProperty("user.dir"));
// ProcessBuilder processBuilder = new ProcessBuilder("claude", "-p", "print out your name", "--json");
ProcessBuilder processBuilder = new ProcessBuilder("node", "-v");
processBuilder.redirectErrorStream(true); // Merge stderr into stdout

System.out.println("Starting Claude process with wrapper script");
Process process = processBuilder.start();

// Read the output in the current thread since we've merged stderr into stdout
StringBuilder outputBuffer = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
outputBuffer.append(line).append("\n");
System.out.println("Claude output: {}"+line);
}
}

System.out.println("Waiting for Claude process to complete");

// Wait for the process to complete with a timeout
boolean completed = process.waitFor(60, TimeUnit.SECONDS);

if (!completed) {
process.destroyForcibly();
throw new TemplateServiceException("Claude shell script execution timed out after 60 seconds");
}

// Check the exit code
int exitCode = process.exitValue();
if (exitCode != 0) {
throw new TemplateServiceException("Claude shell script failed with exit code " + exitCode);
}

System.out.println(outputBuffer.toString());
} catch (Exception e) {
System.err.println("Error running Claude shell script: " + e.getMessage());
e.printStackTrace();
}

  1. The program hangs in line reader.readLine()

Expected Behavior

The Java program should be able to read the output of the claude code and continue without hang.

Actual Behavior

The program hang forever.

Additional Context

If you try to run the Java program with any other commands, it wouldn't hang.

View original on GitHub ↗

This issue has 2 comments on GitHub. Read the full discussion on GitHub ↗