在一次采访中,工作人员询问了并发Hash Map及其功能,我详细解释了这一点。他说,在并发HashMap更新操作的情况下,ConcurrentHashMap只锁定Map的一部分而不是整个Map。
所以他告诉我写一个简单的程序,证明在更新操作期间,ConcurrentHashMap只锁定Map的一部分而不是整个Map。我无法做到这一点,所以请告诉我如何实现这一目标。
答案 0 :(得分:4)
面试官可能期待一个简单的答案,例如:
以下示例输出以下内容:
同步一个线程:30
同步多线程:96
同时一个线程:219
并发多线程:142
所以你可以看到,在高争用(16个线程)下,同步版本的速度要快3倍,而多个线程的并发版本几乎是单个线程的两倍。
值得注意的是,ConcurrentMap在单线程情况下具有不可忽略的开销。
这是一个非常人为的例子,由于微观基准测试而存在所有可能的问题(无论如何都应该丢弃第一批结果)。但它暗示了会发生什么。
public class Test1 {
static final int SIZE = 1000000;
static final int THREADS = 16;
static final ExecutorService executor = Executors.newFixedThreadPool(THREADS);
public static void main(String[] args) throws Exception{
for (int i = 0; i < 10; i++) {
System.out.println("Concurrent one thread");
addSingleThread(new ConcurrentHashMap<Integer, Integer> ());
System.out.println("Concurrent multiple threads");
addMultipleThreads(new ConcurrentHashMap<Integer, Integer> ());
System.out.println("Synchronized one thread");
addSingleThread(Collections.synchronizedMap(new HashMap<Integer, Integer> ()));
System.out.println("Synchronized multiple threads");
addMultipleThreads(Collections.synchronizedMap(new HashMap<Integer, Integer> ()));
}
executor.shutdown();
}
private static void addSingleThread(Map<Integer, Integer> map) {
long start = System.nanoTime();
for (int i = 0; i < SIZE; i++) {
map.put(i, i);
}
System.out.println(map.size()); //use the result
long end = System.nanoTime();
System.out.println("time with single thread: " + (end - start) / 1000000);
}
private static void addMultipleThreads(final Map<Integer, Integer> map) throws Exception {
List<Runnable> runnables = new ArrayList<> ();
for (int i = 0; i < THREADS; i++) {
final int start = i;
runnables.add(new Runnable() {
@Override
public void run() {
//Trying to have one runnable by bucket
for (int j = start; j < SIZE; j += THREADS) {
map.put(j, j);
}
}
});
}
List<Future> futures = new ArrayList<> ();
long start = System.nanoTime();
for (Runnable r : runnables) {
futures.add(executor.submit(r));
}
for (Future f : futures) {
f.get();
}
System.out.println(map.size()); //use the result
long end = System.nanoTime();
System.out.println("time with multiple threads: " + (end - start) / 1000000);
}
}