问题
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