I have a piece of code which uses ProcessBuilder
to run a shell command [cURL] and the response from the command is pretty huge [webpage content].
I am utilising the BufferedReader
to read the response from ProcessBuilder
as shown below
StringBuilder sb = new StringBuilder();
ProcessBuilder processBuilder = new ProcessBuilder();
List<String> args = getArgs("url_to_be_passed"); // Getting my ProcessBuilder args here
processBuilder.command(args);
processBuilder.redirectErrorStream(true);
Process proc = processBuilder.start();
BufferedReader br = null;
try {
InputStream inpc = proc.getInputStream();
/** Beginning of CPU intensive process **/
br = new BufferedReader(new InputStreamReader(inpc));
String line;
while ((line = br.readLine()) != null)
sb.append(line);
/** End of CPU intensive process **/
boolean termination = proc.waitFor(15, TimeUnit.SECONDS);
if (!termination)
throw new SocketTimeoutException("Socket Timed out");
} finally {
if(null != br)
br.close();
proc.destroy();
}
String data = sb.toString(); // Convert data from ProcessBuilder into a String
The getArgs() method is as follows:
private List<String> getArgs(String url) {
List<String> args = new LinkedList<>();
args.add("curl");
args.add("-L");
args.add("--silent");
args.add("--write-out");
args.add("HTTPSTATUS:%{http_code}");
args.add(url);
args.add("-XGET");
args.add("--compressed");
args.add("--connect-timeout");
args.add("10");
return args;
}
I have profiled this piece of code using VisualVM and the screenshot of the CPU intensive process is as shown below:
My queries are as follows:
- What is the best way to convert the response from
ProcessBuilder
into aString
? - If using
BufferedReader
indeed is a good way to read response fromProcessBuilder
, how to make it more CPU friendly?