简体   繁体   English

在Java中使用ProcessBuilder执行外部命令时如何提高性能

[英]How to increase performance when using ProcessBuilder to execute external command in Java

I use ProcessBuilder class to execute external commands in Java. 我使用ProcessBuilder类在Java中执行外部命令。

The code likes below. 代码如下所示。

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true); 
Process process = pb.start(); 
...
// instance a new thread to read process output
...
process.waitFor(); 
...

But If a lot of commands are used to executed by this approach. 但是如果很多命令都被这种方法用来执行。 As waitFor() would cost plenty time, and command executing time would cost more then Linux command line. 由于waitFor()将花费大量时间,而命令执行时间将花费比Linux命令行更多的时间。

Is there any approach to increase the waitfor() performance, or other efficient approach to executing command in java? 是否有任何方法可以提高waitfor()性能,还是在Java中执行命令的其他有效方法?

Is there any approach to increase the waitfor() performance, 有没有什么方法可以提高waitfor()的性能,

No. 没有。

or other efficient approach to executing command in java? 或其他有效的方法来执行命令在Java?

No. 没有。

In fact, assuming that you are reading all of the external command's output, the waitFor() call is unlikely to take much time at all. 实际上,假设您正在读取外部命令的所有输出,则waitFor()调用几乎不可能花费很多时间。

First of all, I think you are doing what is known as "premature optimization". 首先,我认为您正在执行所谓的“过早优化”。 That is, you are trying to optimize something before you know that optimization is required. 也就是说,您在知道需要进行优化之前就尝试进行优化。 Unless you have gotten your code working, measured its performance, and profiled it, you are only guessing that waitFor() in particular and using ProcessBuilder in general are a significant bottleneck. 除非您waitFor()代码正常工作,测量其性能并对其进行waitFor()分析,否则您只会猜测尤其是waitFor()并通常使用ProcessBuilder是一个严重的瓶颈。 If your guess is wrong, then optimization is a waste of time. 如果您的猜测是错误的,那么优化就是浪费时间。


Assuming that that using ProcessBuilder >>is<< a bottleneck, then there is not much you can do about it ... in Java. 假设使用ProcessBuilder <<瓶颈,那么在Java中您无能为力。 Possible non-java solutions are: 可能的非Java解决方案是:

  • Write / rewrite the external application so that you don't need to run multiple commands. 编写/重写外部应用程序,因此您无需运行多个命令。

  • Write a script or batch file, and get >>that<< to run multiple commands. 编写脚本或批处理文件,并获取>> that <<以运行多个命令。

You can take a look at NuProcess . 您可以看一下NuProcess

However, the README states: 但是, README指出:

Speed-wise, there is not a significant difference between NuProcess and the standard Java Process class, even when running 500 concurrent processes. 就速度而言,即使运行500个并发进程,NuProcess与标准Java Process类之间也没有显着差异。 On some platforms such as MacOS X or Linux, NuProcess is 20% faster than java.lang.Process for large numbers of processes. 在某些平台上,例如MacOS X或Linux,对于大量进程,NuProcess比java.lang.Process快20%。

It may be worth a try and see if it helps in your case. 值得一试,看看它是否对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM