Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make Java uses multiple cores with threads?

This is a similar question to the one appearing at: How to ensure Java threads run on different cores. However, there might have been a lot of progress in that in Java, and also, I couldn't find the answer I am looking for in that question.

I just finished writing a multithreaded program. The program spawns several threads, but it doesn't seem to be using more than a single core. The program is faster (I am parallelizing something which makes it faster), but it definitely does not use all cores available, judging by running "top".

Any ideas? Is that an expected behavior?

The general code structure is as following:

   for (some values in i)
   {
        start a thread of instantiated as MyThread(i)
        (this thread uses heavily ConcurrentHashMap and arrays and basic arithmetic, no IO)
        add the thread to a list T
   }

   foreach (thread in T)
   {
        do thread.join()
   }
like image 934
kloop Avatar asked Jul 03 '26 11:07

kloop


1 Answers

If its almost exactly 100% of one CPU, it can mean you really have

  • one core thread which is doing all the work and the others are not doing so much.
  • one resource which you are locking on and only one thread has a chance to run.

If you are using approximately one CPU it can mean this is all the work your CPUs have because you are waiting for something such as IO (network and/or disk)

I suggest you look at the state of your threads in VisualVM. It will help you identify which threads are running and give you an ideal of their pattern of behaviour. I also suggest you use a CPU profiler to help find your bottlenecks.

like image 94
Peter Lawrey Avatar answered Jul 06 '26 01:07

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!