77import me .hsgamer .topper .storage .core .DataStorage ;
88
99import java .util .*;
10+ import java .util .concurrent .ConcurrentHashMap ;
1011import java .util .concurrent .ConcurrentLinkedQueue ;
1112import java .util .concurrent .atomic .AtomicBoolean ;
1213import java .util .concurrent .atomic .AtomicReference ;
@@ -19,6 +20,7 @@ public class StorageAgent<K, V> implements Agent, DataEntryAgent<K, V>, Runnable
1920 private final DataHolder <K , V > holder ;
2021 private final DataStorage <K , V > storage ;
2122 private final Queue <Map .Entry <K , V >> queue = new ConcurrentLinkedQueue <>(); // Value can be null representing removal
23+ private final AtomicReference <Map <K , V >> storeMap = new AtomicReference <>(new ConcurrentHashMap <>());
2224 private final AtomicReference <Map <K , V >> savingMap = new AtomicReference <>();
2325 private final AtomicBoolean saving = new AtomicBoolean (false );
2426 private int maxEntryPerCall = 10 ;
@@ -33,11 +35,10 @@ private void save(boolean urgent) {
3335 if (saving .get () && !urgent ) return ;
3436 saving .set (true );
3537
36- Map <K , V > map = savingMap .get ();
37- if (map == null ) {
38- map = new HashMap <>();
39- }
40- savingMap .set (map );
38+ storeMap .getAndSet (new ConcurrentHashMap <>())
39+ .forEach ((key , value ) -> queue .add (new AbstractMap .SimpleEntry <>(key , value )));
40+
41+ Map <K , V > map = savingMap .updateAndGet (old -> old == null ? new HashMap <>() : old );
4142
4243 for (int i = 0 ; i < (urgent || maxEntryPerCall <= 0 ? Integer .MAX_VALUE : maxEntryPerCall ); i ++) {
4344 Map .Entry <K , V > entry = queue .poll ();
@@ -110,12 +111,12 @@ public void beforeStop() {
110111
111112 @ Override
112113 public void onUpdate (DataEntry <K , V > entry , V oldValue ) {
113- queue . add ( new AbstractMap . SimpleImmutableEntry <> (entry .getKey (), entry .getValue () ));
114+ storeMap . get (). put (entry .getKey (), entry .getValue ());
114115 }
115116
116117 @ Override
117118 public void onRemove (DataEntry <K , V > entry ) {
118- queue . add ( new AbstractMap . SimpleImmutableEntry <> (entry .getKey (), null ) );
119+ storeMap . get (). put (entry .getKey (), null );
119120 }
120121
121122 @ Override
0 commit comments