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?
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.
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.
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();
}
}
}
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.