Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling the IllegalThreadStateException

Tags:

java

import java.io.*;
class Sysexecute
{
    public static void main(String args[]) throws IOException,InterruptedException,IllegalThreadStateException
    {
        Runtime rt= Runtime.getRuntime();
        Process p=rt.exec("ls");
        System.out.println(p.exitValue());
    }
}

i was learning how to execute system commands in java and this error occured. i tried using throws to negate it but was of no use. please explain the reason and solution

actual error:-
Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited
    at java.lang.UNIXProcess.exitValue(UNIXProcess.java:270)
    at Sysexecute.main(Sysexecute.java:8)
like image 944
augustus hill Avatar asked Sep 22 '14 16:09

augustus hill


2 Answers

Invoke Process#waitFor() before trying to get the exit value. This blocks the current thread until the spawned process terminates. If you don't do this, Process#exitValue() throws

IllegalThreadStateException - if the subprocess represented by this Process object has not yet terminated

like image 153
Sotirios Delimanolis Avatar answered Nov 05 '22 17:11

Sotirios Delimanolis


Always use waitFor(long timeout,TimeUnit unit) instead of waitFor(), so that the thread will not be blocked indefinitely.

like image 22
Parthiban Avatar answered Nov 05 '22 16:11

Parthiban