Bench Mark in Multi threaded environment
I've created a simple JMH benchmark to test the various cases:
@Fork(1)
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Measurement(iterations = 10)
@Warmup(iterations = 10)
@BenchmarkMode(Mode.AverageTime)
public class HashCodeBenchmark {
private final Object object = new Object();
@Benchmark
@Threads(1)
public void singleThread(Blackhole blackhole){
blackhole.consume(object.hashCode());
}
@Benchmark
@Threads(2)
public void twoThreads(Blackhole blackhole){
blackhole.consume(object.hashCode());
}
@Benchmark
@Threads(4)
public void fourThreads(Blackhole blackhole){
blackhole.consume(object.hashCode());
}
@Benchmark
@Threads(8)
public void eightThreads(Blackhole blackhole){
blackhole.consume(object.hashCode());
}
}
And the results are as follows:
Benchmark Mode Cnt Score Error Units
HashCodeBenchmark.eightThreads avgt 10 5.710 ± 0.087 ns/op
HashCodeBenchmark.fourThreads avgt 10 3.603 ± 0.169 ns/op
HashCodeBenchmark.singleThread avgt 10 3.063 ± 0.011 ns/op
HashCodeBenchmark.twoThreads avgt 10 3.067 ± 0.034 ns/op
So we can see that as long as there are no more threads than cores, the time per hashcode remains the same.
PS: As @Tom Cools had commented - you are measuring the allocation speed and not the hashCode() speed in your test.