1

I have many threads who save the state and one thread that logs the state.

I'd like to not lose data, which means to always log the latest state.

The solution I have is to use a read-write lock when replacing/clearing the stats collection, which will not loose data but looks very cumbersome. See code below.

What I would like is some way to run some code atomically while an instance isn't changed. Needless to say that the instance change should be atomically as well.

The cumbersome solution (no private, final, static on purpose):

class StatsProvider {
    volatile Set<Status> stats = ConcurrentHashMap.newKeySet();
    ReadWriteLock replaceStatsLock = new ReentrantReadWriteLock();

    void log() {
        replaceStatsLock.writeLock().lock();
        Set<QueueStatus> stats;
        try
        {
            stats = StatsProvider.stats;
            recentQueuesStats = ConcurrentHashMap.newKeySet();
        }
        finally
        {
            replaceStatsLock.writeLock().unlock();
        }
        log(stats);
    }

    void report(Status Status) {
        replaceStatsLock.readLock().lock();
        try
        {
            stats.add(Status);
        }
        finally
        {
            replaceStatsLock.readLock().unlock();
        }
    }
}
AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
  • I don't understand what you're trying to achieve. This code is incomplete, doesn't compile, and seems to use a write lock to read, and a read lock to write, which is quite strange. It also doesn't say what is cumbersome about it. – JB Nizet Nov 26 '18 at 14:02
  • 2
    @JBNizet I think he's trying to get a copy of all the stats, and during that moment he wants no new stat gets added into the collection. Using read lock and write lock like this is strange but correct. – grape_mao Nov 26 '18 at 14:18
  • Thanks @grape_mao. That's exactly what I meant. The lock is on the `stats` class param. Changing it means a write lock. Reading the param means a read lock. – AlikElzin-kilaka Nov 27 '18 at 03:11
  • Does it need to a be a Set? Maybe a Queue would be more appropriate. – shmosel Nov 27 '18 at 03:17
  • @shmosel, Yes, a set in order to not contain duplicate statuses. – AlikElzin-kilaka Nov 27 '18 at 05:39

0 Answers0