java concurrency: many writers, one reader

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

    Another alternative for implement both methods using ReentranReadWriteLock. This implementation protects against race conditions at getStats method, if you need to clear the counters. Also it removes the mutable AtomicLong from the getStats an uses an immutable Long.

    public class StatsService {
    
        private final Map stats = new HashMap(1000);
        private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
        private final Lock r = rwl.readLock();
        private final Lock w = rwl.writeLock();
    
        public void  notify(final String key) {
            r.lock();
            AtomicLong count = stats.get(key);
            if (count == null) {
                r.unlock();
                w.lock();
                count = stats.get(key);
                if(count == null) { 
                    count = new AtomicLong();
                    stats.put(key, count);
                }
                r.lock();
                w.unlock();
            }
            count.incrementAndGet();
            r.unlock();
        }
    
        public Map getStats() {
            w.lock();
    
            Map copy = new HashMap();
            for(Entry entry : stats.entrySet() ){
                    copy.put(entry.getKey(), entry.getValue().longValue());
            }
            stats.clear();
            w.unlock();
    
            return copy;
        }
    }
    

    I hope this helps, any comments are welcome!

提交回复
热议问题