HashMap 和 JDK 7
简单的实验表明,JDK7
编译的HashMap
在执行简单的串行插入查找基准测试时使用许多线程:
- 插入一百万个数字。
- 搜索数亿个数字。
怎么会? JDK7自动猜测如何并行化这段代码???我需要对单线程行为进行基准测试,我该怎么做?
代码,大约加载2.5个核心:
import java.util.*;
public class HashSpeed {
public static void main(String[] args)
{
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(10000);
final int N = 10000000;
for (int i=1; i<N; i+=2)
m.put(i, i);
for (int j=0; j<10; j++) {
for (int i=0; i<N; i++) {
if (m.get(i) != null != (i%2==1)) {
System.out.println("failed");
}
}
}
System.out.println("TEST OK");
}
}
Simple experiment has shown that JDK7
compiled HashMap<Integer, Integer>
uses many threads when performing simple serial insert-find benchmark:
- Insert million numbers.
- Search for hundreds of millions numbers.
How come? JDK7 automatically guesses how to parallelize this code??? I need to benchmark a single-threaded behavior, how could I do it?
Code, about 2.5 cores are loaded:
import java.util.*;
public class HashSpeed {
public static void main(String[] args)
{
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(10000);
final int N = 10000000;
for (int i=1; i<N; i+=2)
m.put(i, i);
for (int j=0; j<10; j++) {
for (int i=0; i<N; i++) {
if (m.get(i) != null != (i%2==1)) {
System.out.println("failed");
}
}
}
System.out.println("TEST OK");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您如何验证
HashMap
代码实际上使用了多个 Java 线程?根据您的描述,听起来您正在查看操作系统级别(例如Windows 的任务管理器)。这可能具有欺骗性。 JVM 可以使用多个线程,例如垃圾收集等。但这并不意味着您正在运行的 Java 代码正在使用多个线程。确定的最简单方法是查看 OpenJDK 源 :-)。
How did you verify that the
HashMap
code is actually using multiple Java threads? From your description, it sounds like you are looking at the OS level (e.g. Task Manager for Windows). This can be deceptive. The JVM can use multiple threads, for things like garbage collection, etc. But that doesn't mean that the Java code you are running is using multiple threads.The easiest way to find out for sure is to look at the OpenJDK source :-).
如果您阅读openjdk源代码(它是开源的)您会发现HashMap不会创建线程。
是什么让你认为它确实如此?
If you read the openjdk source code (it's open source) you'd find that HashMap does not create threads.
What makes you think it does?