返回

java-ConcurrentHashMap锁定值与不锁定获取/删除

发布时间:2022-05-19 21:37:02 272
# 移动端

我看到的代码看起来像这样

    public static void main(String args[]) throws ExecutionException, InterruptedException
    {
        final ConcurrentHashMap map = new ConcurrentHashMap();
        for (int i = 0; i < 10; i++) {
            map.put(String.valueOf(i), String.valueOf(i));
        }

        List futures = new ArrayList<>();
        ExecutorService service = Executors.newFixedThreadPool(10);
        futures.add(service.submit(createTask(map)));
        futures.add(service.submit(createTask(map)));
        futures.add(service.submit(createTask(map)));
        futures.add(service.submit(createTask(map)));
        futures.add(service.submit(createTask(map)));
        futures.add(service.submit(createTask(map)));

        for (Future f : futures) {
            f.get();
        }

        map.keySet().stream().forEach((k) -> {
            System.out.println(String.format("key: %s, value: %s", k, map.get(k)));
        });

        service.shutdown();
    }

    private static Runnable createTask(ConcurrentHashMap map)
    {
        return () -> {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName);
            String value = map.get("1");
            if (value == null) {
                System.out.println(String.format("%s value is null", threadName));
                return;
            }

//            synchronized (value) {
                // do something with the value
                System.out.println(String.format("%s value is %s", threadName, map.remove(value)));
//            }
        };
    }

它锁定ConcurrentHashMap的值get价值和remove当它完成的时候。我试过代码有没有synchronized看起来不管锁定如何,我都会得到相同的结果。我认为在这种情况下,这并不重要,因为remove如果值为null.但我肯定我在比赛条件方面遗漏了一些东西,但我不知道是什么。有没有人能向我解释一下,这段代码在带锁和不带锁的情况下是否存在争用条件方面的问题。

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像