以下微基准测试使用 Guava CacheBuilder。它的执行速度比 ConcurrentHashMap 慢 1 倍。我是否正确使用了 CacheBuilder?
final Cache c = CacheBuilder.newBuilder().concurrencyLevel(10).maximumSize(100).build();
int num = 10;
final java.util.concurrent.CountDownLatch startSignal = new java.util.concurrent.CountDownLatch(1);
final java.util.concurrent.CountDownLatch doneSignal = new java.util.concurrent.CountDownLatch(num);
int j = 0;
final Long[] pairs = new Long[] { new Long(5),
new Long(324235342L), new Long(3242385842L), new Long(8463242363642L),
new Long(3244532342L), new Long(54654L), new Long(7332742342L),
new Long(32425345342L), new Long(32453662342L), new Long(63573242342L) };
Object state = new Object();
for (Long p : pairs) {
c.put(p, state);
}
Thread [] threads = new Thread[num];
for (int k = 0 ; k < num ; ++k) {
final int z = k;
threads[k] = new Thread(new Runnable() {
int i = z;
@Override
public void run() {
try {
startSignal.await();
for (int j = 0 ; j < 100000 ; ++j) {
c.getIfPresent(pairs[z]);
}
doneSignal.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
for (Thread t : threads) {
t.start();
}
startSignal.countDown();
c.getIfPresent(pairs[1]);
long t = System.currentTimeMillis();
doneSignal.await();
System.out.println("done in " + (System.currentTimeMillis() - t));
ConcurrentHashMap 给了我 9 毫秒。CacheBuilder 给了我 90 毫秒。这是在循环相同的代码几分钟之后。