How to replace a concurrently instance without losing data?

丶灬走出姿态 提交于 2019-12-08 03:16:55

问题


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();
        }
    }
}

来源:https://stackoverflow.com/questions/53482673/how-to-replace-a-concurrently-instance-without-losing-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!