java concurrency: many writers, one reader

前端 未结 9 2195
我寻月下人不归
我寻月下人不归 2021-01-30 18:22

I need to gather some statistics in my software and i am trying to make it fast and correct, which is not easy (for me!)

first my code so far with two classes, a StatsS

9条回答
  •  青春惊慌失措
    2021-01-30 18:59

    As jack was eluding to you can use the java.util.concurrent library which includes a ConcurrentHashMap and AtomicLong. You can put the AtomicLong in if absent else, you can increment the value. Since AtomicLong is thread safe you will be able to increment the variable without worry about a concurrency issue.

    public void notify(String key) {
        AtomicLong value = stats.get(key);
        if (value == null) {
            value = stats.putIfAbsent(key, new AtomicLong(1));
        }
        if (value != null) {
            value.incrementAndGet();
        }
    }
    

    This should be both fast and thread safe

    Edit: Refactored sligthly so there is only at most two lookups.

提交回复
热议问题