本文介绍了如何在多线程应用程序中自动更新ConcurrentMap的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ConcurrentMap,我需要从多线程应用程序中填充它.我的地图如下所示:

I have a ConcurrentMap which I need to populate from multithread application. My map is shown below:

  private final ConcurrentMap<String, AtomicLongMap<String>> deviceErrorHolder = Maps.newConcurrentMap();

下面是我的方法,它以非常快的速度从多线程应用程序中调用,因此我需要确保它是快速的.

Below is my method which is called from multithreaded application at very fast rate so I need to make sure it is fast.

  public void addDeviceErrorStats(String deviceName, String errorName) {
    AtomicLongMap<String> errorMap = deviceErrorHolder.get(deviceName);
    if (errorMap == null) {
      errorMap = AtomicLongMap.create();
      AtomicLongMap<String> currenttErrorMap = deviceErrorHolder.putIfAbsent(deviceName, errorMap);
      if (currenttErrorMap != null) {
        errorMap = currenttErrorMap;
      }
    }
    errorMap.incrementAndGet(errorName);
  }

对于每个deviceName,我将有一个AtomicLongMap,其中将包含不同errorName的所有计数.

For each deviceName, I will have an AtomicLongMap which will contain all the counts for different errorName.

  ExceptionCounter.getInstance().addDeviceErrorStats("deviceA", "errorA");
  ExceptionCounter.getInstance().addDeviceErrorStats("deviceA", "errorB");
  ExceptionCounter.getInstance().addDeviceErrorStats("deviceA", "errorC");

  ExceptionCounter.getInstance().addDeviceErrorStats("deviceB", "errorA");
  ExceptionCounter.getInstance().addDeviceErrorStats("deviceB", "errorB");

我的addDeviceErrorStats方法线程安全吗?另外,我更新deviceErrorHolder映射的值的方式是否正确?意味着这将是原子操作吗?我是否需要同步新的AtomicLongMap实例的创建?还是CM会照顾我呢?

Is my addDeviceErrorStats method thread safe? And also the way I am updating the value of my deviceErrorHolder map is correct? Meaning will it be an atomic operation? Do I need to synchronize creation of new AtomicLongMap instances? Or CM will take care that for me?

我正在使用Java7.

I am working with Java7.

推荐答案

您可以使用computeIfAbsent()创建更简单的 lot 版本.

You can create a lot simpler version of this with computeIfAbsent().

AtomicLongMap<String> errorMap = deviceErrorHolder.computeIfAbsent(deviceName, a -> AtomicLongMap.create());
errorMap.incrementAndGet(errorName);

computeIfAbsent(在并发映射中)特别意味着要执行您的null检查逻辑所执行操作的原子版本.如果deviceName键具有值,则将其返回,否则将自动调用该计算,并且该计算的返回值既与映射中的键相关联,也被返回.

The computeIfAbsent (in concurrent maps) is especially meant to do an atomic version of what your null checking logic does. If the deviceName key has a value, it's returned, otherwise the computation is called atomically, and the return value of the computation is both associated with the key in the map as well as returned.

这篇关于如何在多线程应用程序中自动更新ConcurrentMap的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:18