2009年1月20日星期二

Is Java ready for multi-cores?

The title is a little big. -_-

Nowadays most computers have two independent CPU cores, for example, my MacBook has two in the Intel Core 2 Duo. Question is: Can we get any benefits from the additional core when coding with Java? Assuming we programmers take care of threading and algorithm parallelization.

The key to this question is whether we can run two Java threads simultaneously on different cores. In C/C++, we can use SetThreadAffinityMask() for Windows and thread_processor_bind_np() in POSIX systems like Linux. Is there similar mechanism in Java threading? A Google search brings up some relevant pages, like this article by Patrick on JavaWorld. Patrick argued that Java 1.1.3 VM cannot utilize more than 2 CPUs well (Oops, I have only 2..).

To get my hands dirty, I wrote a small program in Java to see if it can use all my cores.


public class MultiCoreWorker extends Thread {

@Override
public void run() {
int a = 0;
while (true) {
a = (a + 1) % 1000;
}
}

public static void main(String[] args)
throws InterruptedException {
MultiCoreWorker t1 = new MultiCoreWorker();
MultiCoreWorker t2 = new MultiCoreWorker();

t1.start();
t2.start();
Thread.sleep(1000000000);
}

}


The code basically do nothing but adding a number, which will take all available CPU cycles. When 2 MultiCoreWorker are running, the system have a 100% CPU usage on both cores. I ran the code multiple times to assure that it's stable. A screenshot of the Activity Monitor is as follows.


It seems at least Java threads can expand on 2 cores well ( On Mac OS X leopard with client JVM 6.0). I'll try to make some of my code parallel and see how much time can it saves by utilizing 2 cores.

The funny thing happened when running just a single thread. I commented out the codes with t2, and re-ran the program. Only one core was used, that's not beyond our expection. Interesting thing is in the following screenshot, the thread was actually jumping between the cores.

See the complementary curves just under the label "CPU Usage" ? :) Our code do not have any I/O operation, so there would be no I/O waiting. It clearly indicates that JVM can move threads between CPUs at any time. Cool...

2 条评论:

匿名 说...

This phenomenon is similar to my experience with hyper-thread wintel computer (2 real core x 2 virtual core). The Great Jump (GJ) occurred for any single thread (not Java). But the GJ was only between two virtual CPUs of one real CPU. You may have more test to find out if the GJ is due to Java or the OS level.
Please continue the discussion as new posts but not comments, since I only use RSS reader.

Luo Yang 说...

Core i7 and Win7 will resolve the GJ issue...