views:

803

answers:

4

Hi,

Say I have a dual-core windows laptop and I run a multithreaded application on it. Does the JVM run only on one core or do the JVM and the OS somehow communicate to split threads between the two cores?

A similar question has been asked for C#. I've also had a look into a couple of Sun's performance white papers. I read that threads can be executed inside kernel threads on Sun servers but what I'm really interested on is non-Sun machines. I also read about Simulatenous Multithreading which seems to be what I'm interested in.

+6  A: 

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.

Nat
A: 

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.

Xepoch
+1  A: 

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.

brianegge
Thanks, I followed your suggestion but instead of running the benchmark, I wrote a quick test class with two threads.
tilish
+1  A: 

Just to follow up, when I run this code on my dual core, I see 100% CPU Usage. When one thread is being used, I see that one CPU gets used 100% and another about 4% (I guess other processes are running on this one).

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