【发布时间】:2015-01-31 00:20:45
【问题描述】:
我正在尝试对一个简单的 Java 应用程序进行多线程处理的不同方法进行基准测试,该应用程序将迭代器的每个元素转换为另一个元素。
以下哪种方式(java 8 并行流、使用 lambda 运算符的常规多线程)最有效?根据下面的输出,似乎并行流与传统的多线程一样好,对吗?
以下代码的输出(您必须将 alice.txt 替换为另一个文件)是:
153407 30420
以毫秒为单位的时间 - 4826
153407 30420
以毫秒为单位的时间 - 37908
153407 30420
以毫秒为单位的时间 - 37947
153407 30420
以毫秒为单位的时间 - 4839
public class ParallelProcessingExample {
public static void main(String[] args) throws IOException{
String contents = new String(Files.readAllBytes(
Paths.get("impatient/code/ch2/alice.txt")), StandardCharsets.UTF_8);
List<String> words = Arrays.asList(contents.split("[\\P{L}]+"));
long t=System.currentTimeMillis();
Stream<String> wordStream = words.parallelStream().map(x->process(x));
String[] out0=wordStream.toArray(String[]::new);
System.out.println(String.join("-", out0).length()+"\t"+out0.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
t=System.currentTimeMillis();
wordStream = words.stream().map(x->process(x));
String[] out1=wordStream.toArray(String[]::new);
System.out.println(String.join("-", out1).length()+"\t"+out1.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
t=System.currentTimeMillis();
String[] out2=new String[words.size()];
for(int j=0;j<words.size();j++){
out2[j]=process(words.get(j));
}
System.out.println(String.join("-", out2).length()+"\t"+out2.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
t=System.currentTimeMillis();
int n = Runtime.getRuntime().availableProcessors();
String[] out3=new String[words.size()];
try {
ExecutorService pool = Executors.newCachedThreadPool();
for(int i=0;i<n;i++){
int from=i*words.size()/n;
int to=(i+1)*words.size()/n;
pool.submit(() -> {
for(int j=from;j<to;j++){
out3[j]=process(words.get(j));
}
});
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.HOURS);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(String.join("-", out3).length()+"\t"+out3.length);
System.out.println("time in ms - "+(System.currentTimeMillis()-t));
}
private static String process(String x) {
try {
TimeUnit.NANOSECONDS.sleep(1);
//Thread.sleep(1); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
return x.toUpperCase();
}
}
【问题讨论】:
-
这可能在 [Code Review](codereview.stackexchange.com) 上做得更好,因为它询问的是优化性能特征,而不是构建功能。
-
你遇到的一个问题是性能方面已经下降了;您没有考虑 JIT。
-
@Nathan,也将其置于代码审查中。但错误问题可能与此处有关。
-
@fge,我不关注。你说的是异常错误还是性能问题?
-
性能问题。 JIT 只会在执行一定数量的代码后才会启动;你根本不考虑这一点。这就是存在 jmh 或 caliper 等工具的原因。
标签: java multithreading lambda java-8 java-stream