Added StorageFolder#getAndCloneData

This commit is contained in:
Felix Cravic 2020-05-04 19:35:52 +02:00
parent 7881e3ca76
commit cad5dfb8eb

View File

@ -42,33 +42,71 @@ public class StorageFolder {
this.storageSystem.close(); this.storageSystem.close();
} }
public synchronized void getAndCacheData(String key, DataContainer dataContainer, Runnable callback) { public void getAndCloneData(String key, DataContainer dataContainer, Runnable callback) {
synchronized (cachedData) {
// Keep giving the same SerializableData if already loaded // Copy data from the cachedMap
if (cachedData.containsKey(key)) { if (cachedData.containsKey(key)) {
dataContainer.setData(cachedData.get(key)); SerializableData data = cachedData.get(key);
if (callback != null) dataContainer.setData(data.clone());
callback.run(); if (callback != null)
return; callback.run();
} return;
// Load it from the storage system
get(key, bytes -> {
SerializableData data;
if (bytes != null) {
data = DataReader.readData(Unpooled.wrappedBuffer(bytes));
} else {
data = new SerializableData();
} }
dataContainer.setData(data); // Load it from the storage system
get(key, bytes -> {
SerializableData data;
this.cachedData.put(key, data); if (bytes != null) {
data = DataReader.readData(Unpooled.wrappedBuffer(bytes));
} else {
data = new SerializableData();
}
if (callback != null) dataContainer.setData(data);
callback.run();
}); if (callback != null)
callback.run();
});
}
}
public void getAndCloneData(String key, DataContainer dataContainer) {
getAndCloneData(key, dataContainer, null);
}
public void getAndCacheData(String key, DataContainer dataContainer, Runnable callback) {
synchronized (cachedData) {
// Give the cached SerializableData if already loaded
if (cachedData.containsKey(key)) {
dataContainer.setData(cachedData.get(key));
if (callback != null)
callback.run();
return;
}
// Load it from the storage system and cache it
get(key, bytes -> {
SerializableData data;
if (bytes != null) {
data = DataReader.readData(Unpooled.wrappedBuffer(bytes));
} else {
data = new SerializableData();
}
dataContainer.setData(data);
this.cachedData.put(key, data);
if (callback != null)
callback.run();
});
}
} }
public void getAndCacheData(String key, DataContainer dataContainer) { public void getAndCacheData(String key, DataContainer dataContainer) {
@ -77,11 +115,13 @@ public class StorageFolder {
public void saveCachedData() { public void saveCachedData() {
try { try {
for (Map.Entry<String, SerializableData> entry : cachedData.entrySet()) { synchronized (cachedData) {
String key = entry.getKey(); for (Map.Entry<String, SerializableData> entry : cachedData.entrySet()) {
SerializableData data = entry.getValue(); String key = entry.getKey();
SerializableData data = entry.getValue();
set(key, data.getSerializedData()); set(key, data.getSerializedData());
}
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();