简体   繁体   中英

Using ConcurentHashMap and AtomicInteger as instance variables within a spring service class

I am attempting to implement thread-safe usage of ConcurentHashMap within singleton spring service that is injected into controllers:

@Service
public MyService{

  final ConcurrentMap<String, AtomicInteger> myMap = new ConcurrentHashMap<String,   AtomicInteger>(10) {
        {/* initialize the ten key/values */
        }
    };

 public int add(String key) {
   return myMap.get(key).incrementAndGet();
 }

    // accessed via ajax loop (and controller), if value changes update display
  public int getCount(String key) {
    return myMap.get(key).get();
  }
}

Is there a better way to make access to a hashmap thread-safe? How could I adapt this to work in a clustered environment? It is a follw up to my other question.

I do not aim to have an answer for the question esp. because I do not have expertise in the clustered situation; however, I'd like to point out what I think is worth noticing.

@JB Nizet in one of the comments mentions that the code is thread-safe and correct . I would like to add but not consistent based on Java API Reference :

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove)

It means that there can be a client getting this information while some update is currently running. And, that makes sense since you mention 'looping' in your code. So, if this is NOT important in your case, then everything should be just fine.

But, if you need to make this more strict, I was thinking maybe using an instance of ReentrantReadWriteLock would be a good choice. The lock enables your code to block all the read requests until there is a consistent snapshot of the information available. You'd be probably using the lock on the getCount method to strictly block until add method frees all the locks waiting for the consistent snapshot of the map used in the code.

I also have a guess that the same concern is valid when you migrate this to a clustered solution; if consistency is required across different cluster nodes, then it should be taken care of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM