我想了解多線程環境中的性能。爲此我寫了一個小測試,在我的機器上運行(四核英特爾,Windows XP,Sun JDK 1.6.0_20),結果令人驚訝。多線程Java應用程序的性能
測試基本上是使用任一關鍵字或一個顯式鎖定同步的線程安全計數器。下面是代碼:
import java.util.concurrent.locks.ReentrantLock;
public class SynchronizedPerformance {
static class Counter {
private static final int MAX = 1 << 24;
int count;
long lastLog = 0;
private final ReentrantLock lock = new ReentrantLock();
private int incrementAndGet() {
count++;
if (count == MAX) {
long now = System.nanoTime();
if (lastLog != 0) {
long elapsedTime = now - lastLog;
System.out.printf("counting took %.2f ns\n", Double.valueOf((double)elapsedTime/MAX));
}
lastLog = now;
count = 0;
}
return count;
}
synchronized int synchronizedIncrementAndGet() {
return incrementAndGet();
}
int lockedIncrementAndGet() {
lock.lock();
try {
return incrementAndGet();
} finally {
lock.unlock();
}
}
}
static class SynchronizedCounterAccessor implements Runnable {
private final Counter counter;
public SynchronizedCounterAccessor(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
while (true)
counter.synchronizedIncrementAndGet();
}
}
static class LockedCounterAccessor implements Runnable {
private final Counter counter;
public LockedCounterAccessor(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
while (true)
counter.lockedIncrementAndGet();
}
}
public static void main(String[] args) {
Counter counter = new Counter();
final int n = Integer.parseInt(args[0]);
final String mode = args[1];
if (mode.equals("locked")) {
for (int i = 0; i < n; i++)
new Thread(new LockedCounterAccessor(counter), "ca" + i).start();
} else if (mode.equals("synchronized")) {
for (int i = 0; i < n; i++)
new Thread(new SynchronizedCounterAccessor(counter), "ca" + i).start();
} else {
throw new IllegalArgumentException("locked|synchronized");
}
}
}
我提出以下意見:
java SynchronizedPerformance 1 synchronized
工作得很好,並採取每步大約15納秒。java SynchronizedPerformance 2 synchronized
干擾很多,每步大約需要150 ns。- 當我開始的
java SynchronizedPerformance 2 synchronized
兩個獨立的過程它們中的每需要每步大約100納秒。也就是說,第二次啓動過程會使第一個(和第二個)更快。
我不明白第三觀察。這種現象存在什麼合理的解釋?
你需要重複運行的微基準測試,否則自然變異會在測量中壓倒任何實際信號。運行數十次或數百次。 – 2010-10-26 22:09:53
我已經做了。效果是一樣的。特別是在場景3中,當我只啓動一個進程時,應用程序很慢,而且每當我啓動第二個進程時,應用程序都會更快。當我稍後停止第二個過程時,第一個過程再次變慢。 – 2010-10-27 06:02:37