Search code examples
javaprocesstimeoutprocessbuilderinterrupted-exception

Why is Java.lang.Process not throwing InterruptedException in this code?


This method uses ProcessBuilder to run an external C program through my Java application. I have set it to wait for 1000 ms. I'm passing it a code that goes into infinite loop. But the process never throws interruptedException.

    public void execute(String sourceFileName, long timeout,String inputFile,String outputFile,String errorFile) 
            throws IOException, InterruptedException
    {
        ProcessBuilder builder=new ProcessBuilder(sourceFileName+executableFileExtension);
        Process process=builder.start();
        process.waitFor(timeout,TimeUnit.MILLISECONDS);
    }   

I also noticed that the method returns the control but the process keeps running in the background. Why does this happen?


Solution

  • method returns the control but the process keeps running in the background - because you have specified a timeout limit and by that time, your C program has not finished. You yourself saying that its an infinite loop.

    I'm passing it a code that goes into infinite loop. But the process never throws interruptedException.

    waitFor()

    documentation says that

    Throws: InterruptedException - if the current thread is interrupted by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

    Your current thread is not interrupted by any other Thread so it doesn't throw InterruptedException.

    Your program's behavior doesn't seem erroneous.