0

I just got into executing batch programs from Java. I was trying to make a converter program poll a directory so that the files would automatically be converted by ffmpeg and sent to an output directory. I wrote something along the lines of this...

    Process p = Runtime.getRuntime().exec("ffmpeg args args args args....");
    p.waitFor();

And this is how I would do something with a Thread

    Thread threadThlinstone = new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            // Do thing!
        }
    }).start();
    threadThlinstone.join();

Besides the fact that one creates a new JVM to execute the task, and instances of the JVM can share memory, is there anything fundamentally different between these two code examples?

  • possible duplicate of [What is the difference between a process and a thread](http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread) – azurefrog Aug 12 '14 at 17:38

1 Answers1

0

The first one creates a new process. It's not necessarily going to be a new JVM, though; you won't get another JVM unless you're running another Java program. In your example, you're invoking ffmpeg, which is a native binary, so it won't run inside a JVM.

The second one starts a new thread going, which is part of your existing program. That means it shares memory with the main program. It also means that if your main program terminates, the thread will terminate too (which isn't true in your first example).

The second is a more efficient way of doing work, because it's quite heavy duty to invoke an external program, and also causes more potential security problems. If you can do what you want to do inside the Java environment, the second approach is better.

But the second one, as it stands, is largely pointless. You start a new thread, get it to do some stuff, and then wait for it to finish. If you're doing that, you might just as well do the work without creating a new thread. The only reason for creating a new thread is so that it can do things in the background without having to wait for it to finish.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
  • "It also means that if your main program terminates, the thread will terminate too." Not true, because the second thread is a regular thread (i.e., not a daemon thread). The JVM will continue to run as long as at least one non-daemon still is running. It doesn't matter whether the main thread is one of them or not. – Solomon Slow Aug 12 '14 at 21:59
  • Well, then I guess that it's good that this is just an example! xD. I typically start multiple threads and wait for them to finish using an ExecutorService, but I was using this example for the sake of argument. So, does this mean that an OS has a built in understanding of what a thread is? – user3925332 Aug 13 '14 at 01:15