kloop
kloop

Reputation: 4721

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()
   }

Upvotes: 3

Views: 2761

Answers (2)

enTropy
enTropy

Reputation: 621

I think I read in the SCJP book by Katherine Sierra that JVM's ask the underlying OS to create a new OS thread for every Java thread.

So it's up to the underlying Operating System to decide how to balance Java (and any other kind of) threads between the available CPU's.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

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.

Upvotes: 4

Related Questions