2009年1月27日星期二

在Java中检测cpu数目

如果我们想在Java中利用多核处理器,那么就要按照实际的处理器数目来创建线程。如何得到处理器数目呢?一句话: Runtime.getRuntime().availableProcessors(); 这是一个int值,在我的macbook上返回的就是2,呵呵,简单方便。

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...