3

I'm writing an app in java allowing me to run other applications. To do that, I've used an Process class object, but when I do, the app awaits the process to end before exiting itself. Is there a way to run external application in Java, but don't wait for it to finish?

public static void main(String[] args)
{
FastAppManager appManager = new FastAppManager();
appManager.startFastApp("notepad");
}

public void startFastApp(String name) throws IOException
{
    Process process = new ProcessBuilder(name).start(); 
}
Daniel Cisek
  • 931
  • 3
  • 9
  • 23

2 Answers2

3

ProcessBuilder.start() does not wait for process to finish. You need to call Process.waitFor() to get that behaviour.

I did a small test with this program

public static void main(String[] args) throws IOException, InterruptedException {
    new ProcessBuilder("notepad").start();
}

When run in netbeans it appear to be still running. When running from command line with java -jar it returns immediately.

So your program is probably not waiting to exit, but your IDE makes it seem so.

Esben Skov Pedersen
  • 4,437
  • 2
  • 32
  • 46
0

You can run it in another thread.

  public static void main(String[] args) {
        FastAppManager appManager = new FastAppManager();
        appManager.startFastApp("notepad");
    }

    public void startFastApp(final String name) throws IOException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Process process = new ProcessBuilder(name).start();
                } catch (IOException e) {
                    e.printStackTrace();  
                }

            }
        });

    }

You might want to start a daemon thread depending on your needs:

ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread();
            thread.setDaemon(true);
            return thread;
        }
    });
ebaxt
  • 8,287
  • 1
  • 34
  • 36