I studied multithreading and found a slowdown in Object.hashCode in a multithreaded environment, since it takes twice as long to calculate the default hash code that executes 4 threads vs 1 thread for the same number of objects.
But, according to my understanding, parallel execution should be performed in parallel.
You can change the number of threads. Each thread does the same job, so you can hope that starting 4 threads on my machine, which is a quad-core machine, can take about the same time as a single thread.
I see ~ 2.3 seconds for 4x, but 0.9 s for 1x.
Is there a gap in my understanding, please help me understand this behavior.
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(); } } }
Number of threads 4 Exit
~2.3 seconds
Number of threads 1 Output
~.9 seconds
java multithreading executorservice microbenchmark
Show stopper
source share