test/java/rmi/testlibrary/JavaVM.java

Print this page
rev 9291 : 8032050: Clean up for java/rmi/activation/Activatable/shutdownGracefully/ShutdownGracefully.java
Reviewed-by: smarks

@@ -24,10 +24,11 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.util.Arrays;
 import java.util.StringTokenizer;
+import java.util.concurrent.TimeoutException;
 
 /**
  * RMI regression test utility class that uses Runtime.exec to spawn a
  * java process that will run a named java class.
  */

@@ -171,10 +172,44 @@
         errPipe.join();
         return status;
     }
 
     /**
+     * Causes the current thread to wait the vm process to exit, if necessary,
+     * wait until the vm process has terminated, or the specified waiting time
+     * elapses. Release allocated input/output after vm process has terminated.
+     * @param timeout the maximum milliseconds to wait.
+     * @return exit value for vm process.
+     * @throws InterruptedException if the current thread is interrupted
+     *         while waiting.
+     * @throws TimeoutException if subprocess does not end after timeout
+     *         milliseconds passed
+     */
+    public int waitFor(long timeout)
+            throws InterruptedException, TimeoutException {
+        if (vm == null)
+            throw new IllegalStateException("can't wait for JavaVM that isn't running");
+        long startTime = System.currentTimeMillis();
+        long rem = timeout;
+
+        do {
+            try {
+                int status = vm.exitValue();
+                outPipe.join();
+                errPipe.join();
+                return status;
+            } catch (IllegalThreadStateException ex) {
+                if (rem > 0) {
+                    Thread.sleep(Math.min(rem, 100));
+                }
+            }
+            rem = timeout - (System.currentTimeMillis() - startTime);
+        } while (rem > 0);
+        throw new TimeoutException();
+    }
+
+    /**
      * Starts the subprocess, waits for it to exit, and returns its exit status.
      */
     public int execute() throws IOException, InterruptedException {
         start();
         return waitFor();