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?
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.
On top of my head, reasons for using processes
as a complement to threads
could be
Still, in most applications threading
is the preferred tool for memory reasons, easy to spawn and its (relatively) simple ease of use.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With