While trying to debug why my multi threaded Java application is consuming large amount of CPU I found that each thread executes an external command which is not at all CPU intensive but when Java runs it, I find Java runtime taking 100% of my CPU.
To further debug, I’ve replaced that external process with simple Linux “ls” command. here is how I am running it-
String[] commands = new String[]{"/bin/sh", "-c", "ls"};
try {
Process p = Runtime.getRuntime().exec(commands);
} catch (IOException ex) {
//
}
Still, I see Java using all of the CPU.
I am not even reading any output from process, nor opening any sort of stream.
What could be wrong? How come a simple ls command when run externally from Java is causing Java runtime to consume large CPU?
Instead of running external command, to simulate thread processing, I tried putting Thread.Sleep() and it works fine- no more CPU hog
Looks like a known issue, I guess I would need to use this- https://github.com/axiak/java_posix_spawn
Update:
After using java_posix_spawn, problem is gone!