private ProcessResult waitFor ( WaitForProcess task ) throws IOException , InterruptedException , TimeoutException { ProcessResult result ; if ( timeout == null ) { // Use the current thread result = task . call ( ) ; } else { // Fork another thread to invoke Process.waitFor() ExecutorService service = newExecutor ( task ) ; // Copy values to not conflict with further executions long _timeout = timeout ; TimeUnit unit = timeoutUnit ; try { result = invokeSubmit ( service , task ) . get ( _timeout , unit ) ; } catch ( ExecutionException e ) { Throwable c = e . getCause ( ) ; if ( c instanceof IOException ) { throw ( IOException ) c ; } if ( c instanceof InterruptedException ) { throw ( InterruptedException ) c ; } if ( c instanceof InvalidExitValueException ) { InvalidExitValueException i = ( InvalidExitValueException ) c ; throw new InvalidExitValueException ( i . getMessage ( ) , i . getResult ( ) ) ; } if ( c instanceof InvalidOutputException ) { InvalidOutputException i = ( InvalidOutputException ) c ; throw new InvalidOutputException ( i . getMessage ( ) , i . getResult ( ) ) ; } if ( c . getClass ( ) . equals ( InvalidResultException . class ) ) { InvalidResultException p = ( InvalidResultException ) c ; throw new InvalidResultException ( p . getMessage ( ) , p . getResult ( ) ) ; } throw new IllegalStateException ( "Error occured while waiting for process to finish:" , c ) ; } catch ( TimeoutException e ) { messageLogger . message ( log , "{} is running too long" , task ) ; throw newTimeoutException ( _timeout , unit , task ) ; } finally { // Interrupt the task if it's still running and release the ExecutorService's resources service . shutdownNow ( ) ; } } return result ; }
Wait until the process stops a timeout occurs and the caller thread gets interrupted . In the latter cases the process gets destroyed as well .