为什么ConcurrentHashMap :: putIfAbsent比ConcurrentHashMap :: computeIfAbsent更快?

时间:2016-10-17 08:13:48

标签: java performance

使用ConcurrentHashMap,我发现computeIfAbsent比putIfAbsent慢两倍。这里简单的测试:

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;


public class Test {
    public static void main(String[] args) throws Exception {
        String[] keys = {"a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a0", "a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a00"};

        System.out.println("Test case 1");
        long time = System.currentTimeMillis();
        testCase1(keys);
        System.out.println("ExecutionTime: " + String.valueOf(System.currentTimeMillis() - time));

        System.out.println("Test case 2");
        time = System.currentTimeMillis();
        testCase2(keys);
        System.out.println("ExecutionTime: " + String.valueOf(System.currentTimeMillis() - time));

        System.out.println("Test case 3");
        time = System.currentTimeMillis();
        testCase3(keys);
        System.out.println("ExecutionTime: " + String.valueOf(System.currentTimeMillis() - time));
    }

    public static void testCase1(String[] keys) throws InterruptedException {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

        List<Thread> threads = new ArrayList<>();

        for (String key : keys) {
            Thread thread = new Thread(() -> map.computeIfAbsent(key, s -> {
                System.out.println(key);
                String result = new TestRun().compute();
                System.out.println("Computing finished for " + key);
                return result;
            }));
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }
    }

    public static void testCase2(String[] keys) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();

        for (String key : keys) {
            Thread thread = new Thread(() -> {
                System.out.println(key);
                new TestRun().compute();
                System.out.println("Computing finished for " + key);
            });
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }
    }


    public static void testCase3(String[] keys) throws InterruptedException {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

        List<Thread> threads = new ArrayList<>();

        for (String key : keys) {
            Thread thread = new Thread(() -> {
                Callable<String> c = () -> {
                    System.out.println(key);
                    String result = new TestRun().compute();
                    System.out.println("Computing finished for " + key);
                    return result;
                };

                try {
                    map.putIfAbsent(key, c.call());
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                }
            });
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }
    }

}

class TestRun {
    public String compute() {
        try {
            Thread.currentThread().sleep(5000);
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return UUID.randomUUID().toString();
    }
}

在我的笔记本电脑上运行此测试,testCase1(使用computeIfAbsent())执行时间是10068ms,对于testCase2(它执行相同的东西,但没有将它包装到computeIfAbsent())执行时间是5009ms(当然它变化了位,但主要趋势是这样)。最有趣的是testCase3 - 它与testCase1几乎相同(除了使用putIfAbsent()而不是computeIfAbsent()),但它的执行速度提高了两倍(testCase3为5010ms,testCase1为10068ms)。

查看源代码,对于computeIfAbsent()和putVal()(在引擎盖下的putIfAbsent()中使用),它几乎相同。

有人知道造成线程执行时间不同的原因吗?

1 个答案:

答案 0 :(得分:2)

您遇到了记录功能:

  

计算正在进行时,其他线程可能会阻止此地图上的某些尝试更新操作,因此计算应该简短,并且不得尝试更新此映射的任何其他映射。

computeIfAbsent检查密钥存在并锁定映射的某些部分。然后它调用functor并将结果放入map(如果返回的值不为null)。只有在那之后,这部分地图才被解锁。

另一方面,test3总是调用c.call(),计算结束后调用putIfAbsent。