Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need multiprocess programming in Java?

Java supports multithread well, and Java also supports multiprocess via Process, ProcessBuilder and Runtime.exec()...

I know clearly the definitions of thread and process, and the differences between them in os concepts.

But I wonder why and in what situation do we need to use a multiprocess instead of multithread in Java application?

like image 477
Jingjing Zhong Avatar asked Sep 17 '12 06:09

Jingjing Zhong


4 Answers

Don't necessarily think of processes as replacements for threads. Processes in java are convenient ways of executing external commands. They aren't really that useful in general parallelism scenarios, as they are cumbersome to start and synchronize.

Another good use of them is to isolate native code (or any other code that you cannot control) that may not terminate or cause stack overflows. If this were to be run inside a thread it could bring the entire process down. Instead, you can spawn a new process and then forcibly kill it without worrying to much about it.

like image 169
Tudor Avatar answered Sep 23 '22 23:09

Tudor


On top of my head, reasons for using processes as a complement to threads could be

  • Robustness, one failing process won't affect another
  • Separation. Launching multiple JVM allows running the same classes without worrying about interference (e.g., easier to use non-thread safe libraries)
  • Generally to be able to launch external commands (e.g., non-java)
  • Thread affinity. In some OS's it might provide better cache semantics with processes shared over multiple CPU's rather than threads, especially when considering a thread-shared working set.

Still, in most applications threading is the preferred tool for memory reasons, easy to spawn and its (relatively) simple ease of use.

like image 30
Johan Sjöberg Avatar answered Sep 22 '22 23:09

Johan Sjöberg


You may need it when synchronization is not an issue, i.e. processes that are not interfering the same data, but you need the outputs of these processes to be collected at the same time, meaning you need to run them in parallel although they are completely different processes.

like image 45
Juvanis Avatar answered Sep 26 '22 23:09

Juvanis


There is no run-away protection in the JVM.

If you have a thread which will not stop, the only way to forcefully stop it, is to have the operating system kill its JVM. By having separate processes you can keep the rest of the application running.

like image 37
Thorbjørn Ravn Andersen Avatar answered Sep 24 '22 23:09

Thorbjørn Ravn Andersen