2

If I write a multi-threaded java application, will the JVM take care of utilizing all available cores? Do I have to do some work?

4 Answers 4

10

Unless you use a JVM that has so-called "green" threads (which is very few these days), Java threads are run by OS threads, so multiple threads get run on different cores by default.

4

To follow up, I see 100% usage on both cores when I run this code on my dual core. If I bring the number of threads from two to one, one core goes to 100% and another about 4%.

package test;

import java.util.ArrayList;

public class ThreadTest
{
    public void startCPUHungryThread()
    {
        Runnable runnable = new Runnable(){
            public void run()
            {
                while(true)
                {
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();     
    }

    public static void main(String[] args)
    {
        ThreadTest thread = new ThreadTest();
        for (int i=0; i<2; i++)
        {
            thread.startCPUHungryThread();
        }
    }
}
1
  • You can't guarentee that they will run on different cores. Oct 25, 2012 at 14:42
2

All modern JVMs will take advantage of as many cores as your hardware has. An easy way to illustrate this is to download and run the DaCapo benchmark on your machine. The lusearch benchmark uses 32 threads. If you run this on your desktop or server, you should see all of your CPUs hit 100% utilization during the test.

1
  • Thanks, I followed your suggestion but instead of running the benchmark, I wrote a quick test class with two threads.
    – tilish
    Nov 2, 2009 at 9:54
0

On the flip of that, it is sometimes useful to "bound"/set affinity for a Java process to only use a set of cores/sockets, though done via OS semantics. As previously answered, most runtimes indeed employ all cpus and with highly threaded apps can eat up more resources than you might expect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.