I have a ConcurrentMap that I need to populate from a multi-threaded application. My map is shown below:
private final ConcurrentMap<String, AtomicLongMap<String>> deviceErrorHolder = Maps.newConcurrentMap();
Below is my method, which is called from a multi-threaded application with a very high speed, 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); }
For each deviceName , I will have AtomicLongMap , which will contain all the calculations 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");
Is addDeviceErrorStats thread addDeviceErrorStats safe? And also the way I update the value of my deviceErrorHolder map, right? Will it be an atomic operation? Do I need to synchronize the creation of new AtomicLongMap instances? Or will CM take care of me?
I am working with Java7.
user5447339
source share