我在学习多线程,发现多线程环境下Object.hashCode的速度变慢,因为它占用了两倍长的时间来计算运行4线程vs 1线程的默认哈希码的物体。多线程环境中的Bench Mark
但根据我的理解,它应该花费相当多的时间来并行处理这个问题。
您可以更改线程数。每个线程都有相同数量的工作,所以希望在我的四核机器上运行4个线程可能需要大约与运行单线程相同的时间。
我看到4x为2.3秒,而1x为0.9秒。
我的理解有没有差距,请帮我理解这种行为。
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
public class ObjectHashCodePerformance {
private static final int THREAD_COUNT = 4;
private static final int ITERATIONS = 20000000;
public static void main(final String[] args) throws Exception {
long start = System.currentTimeMillis();
new ObjectHashCodePerformance().run();
System.err.println(System.currentTimeMillis() - start);
}
private final ExecutorService _sevice = Executors.newFixedThreadPool(THREAD_COUNT,
new ThreadFactory() {
private final ThreadFactory _delegate = Executors.defaultThreadFactory();
@Override
public Thread newThread(final Runnable r) {
Thread thread = _delegate.newThread(r);
thread.setDaemon(true);
return thread;
}
});
private void run() throws Exception {
Callable<Void> work = new java.util.concurrent.Callable<Void>() {
@Override
public Void call() throws Exception {
for (int i = 0; i < ITERATIONS; i++) {
Object object = new Object();
object.hashCode();
}
return null;
}
};
@SuppressWarnings("unchecked")
Callable<Void>[] allWork = new Callable[THREAD_COUNT];
Arrays.fill(allWork, work);
List<Future<Void>> futures = _sevice.invokeAll(Arrays.asList(allWork));
for (Future<Void> future : futures) {
future.get();
}
}
}
对于线程数4输出是
~2.3 seconds
对于线程数1个输出是
~.9 seconds
请分享你的1个4线程 – Jan
之间所做的更改时间测量不一定告诉你很多在这里。查看http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Marco13
你可能不是在衡量正确的事情:GC,创建执行者和它的线程,线程协调,对象实例化,内存分配等等。无论如何,beanchmark是非常没用的,因为无论如何你都不能改变Object的hashCode()实现。 –