How do I design thread-safety in the code

Viewed 68

I have few questions on below code:

  1. How do I access class level map object from REST controller side. This object stores user input, so in controller side map.get(<text>) return count.

  2. Do I still need thread safety from multiple threads using Lock or CountDownLatch in addText method?

private ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<>();
       
public void addText(String text){
    System.out.println("current thread name "+Thread.currentThread().getName());
    AtomicLong l = map.get(text);
    if(l == null){
        l = new AtomicLong(1);
        l = map.putIfAbsent(text, l);
        if(l != null){
            l.incrementAndGet();
        }
    }else{
        l.incrementAndGet();
    }
}
1 Answers
  1. Every call to your Spring ApiRest controller will create a new instance of your object, so no concurrent access to your object.

  2. If, for some reason your object is shared, static ..., your method: 'addText' doesn't have any side effect apart from mutating the map (which is concurrent friendly), so no more thread safety to add IMHO.

-- Edit to respond to comment --

  • To keep in memory you can declare you map as static in some class or just declare it in your Rest Controller as class variable (as controllers are singletons by default if you don't modify scope )
Related