java concurrency: many writers, one reader

前端 未结 9 2091
我寻月下人不归
我寻月下人不归 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 19:07

    Chris Dail's answer looks like a good approach.

    Another alternative would be to use a concurrent Multiset. There is one in the Google Collections library. You could use this as follows:

    private Multiset stats = ConcurrentHashMultiset.create();
    
    public void notify ( String key )
    {
        stats.add(key, 1);
    }
    

    Looking at the source, this is implemented using a ConcurrentHashMap and using putIfAbsent and the three-argument version of replace to detect concurrent modifications and retry.

提交回复
热议问题