Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6354393
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T22:34:07+00:00 2026-05-24T22:34:07+00:00

This question is about java.lang.Process and its handling of stdin, stdout and stderr. We

  • 0

This question is about java.lang.Process and its handling of stdin, stdout and stderr.

We have a class in our project that is an extension to org.apache.commons.io.IOUtils. There we have a quiet new method for closing the std-streams of a Process-Object appropriate? Or is it not appropriate?

/**
 * Method closes all underlying streams from the given Process object.
 * If Exit-Code is not equal to 0 then Process will be destroyed after 
 * closing the streams.
 *
 * It is guaranteed that everything possible is done to release resources
 * even when Throwables are thrown in between.
 *
 * In case of occurances of multiple Throwables then the first occured
 * Throwable will be thrown as Error, RuntimeException or (masked) IOException.
 *
 * The method is null-safe.
 */
public static void close(@Nullable Process process) throws IOException {
    if(process == null) {
      return;
    }

    Throwable t = null;

    try {
      close(process.getOutputStream());
    }
    catch(Throwable e) {
      t = e;
    }

    try{
      close(process.getInputStream());
    }
    catch(Throwable e) {
      t = (t == null) ? e : t;
    }

    try{
      close(process.getErrorStream());
    }
    catch (Throwable e) {
      t = (t == null) ? e : t;
    }

    try{
      try {
        if(process.waitFor() != 0){
          process.destroy();
        }
      }
      catch(InterruptedException e) {
        t = (t == null) ? e : t;
        process.destroy();
      }
    }
    catch (Throwable e) {
      t = (t == null) ? e : t;
    }

    if(t != null) {
      if(t instanceof Error) {
        throw (Error) t;
      }

      if(t instanceof RuntimeException) {
        throw (RuntimeException) t;
      }

      throw t instanceof IOException ? (IOException) t : new IOException(t);
    }
}

public static void closeQuietly(@Nullable Logger log, @Nullable Process process) {
  try {
    close(process);
  }
  catch (Exception e) {
    //log if Logger provided, otherwise discard
    logError(log, "Fehler beim Schließen des Process-Objekts (inkl. underlying streams)!", e);
  }
}

public static void close(@Nullable Closeable closeable) throws IOException {
  if(closeable != null) {
    closeable.close();
  }
}

Methods like these are basically used in finally-blocks.

What I really want to know is if I am safe with this implementation? Considering things like: Does a process object always return the same stdin, stdout and stderr streams during its lifetime? Or may I miss closing streams previously returned by process’ getInputStream(), getOutputStream() and getErrorStream() methods?

There is a related question on StackOverflow.com: java: closing subprocess std streams?

Edit

As pointed out by me and others here:

  • InputStreams have to be totally consumed. When not done then the subprocess may not terminate, because there is outstanding data in its output streams.
  • All three std-streams have to be closed. Regardless if used before or not.
  • When the subprocess terminates normally everything should be fine. When not then it have to be terminated forcibly.
  • When an exit code is returned by subprocess then we do not need to destroy() it. It has terminated. (Even when not necessarily terminated normally with Exit Code 0, but it terminated.)
  • We need to monitor waitFor() and interrupt when timeout exceeds to give process a chance to terminate normally but killing it when it hangs.

Unanswered parts:

  • Consider Pros and Cons of consuming the InputStreams in parallel. Or must they be consumed in particular order?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T22:34:07+00:00Added an answer on May 24, 2026 at 10:34 pm

    Just to let you know what I have currently in our codebase:

    public static void close(@Nullable Process process) throws IOException {
      if (process == null) {
        return;
      }
    
      Throwable t = null;
    
      try {
        flushQuietly(process.getOutputStream());
      }
      catch (Throwable e) {
        t = mostImportantThrowable(t, e);
      }
    
      try {
        close(process.getOutputStream());
      }
      catch (Throwable e) {
        t = mostImportantThrowable(t, e);
      }
    
      try {
        skipAllQuietly(null, TIMEOUT, process.getInputStream());
      }
      catch (Throwable e) {
        t = mostImportantThrowable(t, e);
      }
    
      try {
        close(process.getInputStream());
      }
      catch (Throwable e) {
        t = mostImportantThrowable(t, e);
      }
    
      try {
        skipAllQuietly(null, TIMEOUT, process.getErrorStream());
      }
      catch (Throwable e) {
        t = mostImportantThrowable(t, e);
      }
    
      try {
        close(process.getErrorStream());
      }
      catch (Throwable e) {
        t = mostImportantThrowable(t, e);
      }
    
      try {
        try {
          Thread monitor = ThreadMonitor.start(TIMEOUT);
          process.waitFor();
          ThreadMonitor.stop(monitor);
        }
        catch (InterruptedException e) {
          t = mostImportantThrowable(t, e);
          process.destroy();
        }
      }
      catch (Throwable e) {
        t = mostImportantThrowable(t, e);
      }
    
      if (t != null) {
        if (t instanceof Error) {
          throw (Error) t;
        }
    
        if (t instanceof RuntimeException) {
          throw (RuntimeException) t;
        }
    
        throw t instanceof IOException ? (IOException) t : new IOException(t);
      }
    }
    

    skipAllQuietly(...) consumes complete InputStreams. It uses internally an implementation similar to org.apache.commons.io.ThreadMonitor to interrupt consumption if a given timeout exceeded.

    mostImportantThrowable(...) decides over what Throwable should be returned. Errors over everything. First occured higher prio than later occured. Nothing very important here since these Throwable are most probably discarded anyway later. We want to go on working here and we can only throw one, so we have to decide what we throw at the end, if ever.

    close(...) are null-safe implementations to close stuff but throwing Exception when something went wrong.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This may be a ridiculous Java question about exception handling, but I have a
I have read a lot about the Java class loading process lately. Often I
This question is about a Java JTree or a Window .Net Tree (Winforms) or
This question is about Why does autoboxing make some calls ambiguous in Java? But
I have a question about this question . I posted a reply there but
I have a question about MIMEParsingException. I use Java EE 6 with NetBeans 6.8.
I'm new to Java and have a question about a warning: My general code:
Following my previous question , i have a question about why is it this
This question is a follow up to my previous question about getting the HTML
I was reading this question about how to parse URLs out of web pages

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.