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");
}
}
How did you verify that the
HashMapcode 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 :-).