From c62634de923a96e47c01458eb6c68c88ca9eafb1 Mon Sep 17 00:00:00 2001 From: 0xb00bface <0xboobface@gmail.com> Date: Tue, 25 Apr 2023 20:45:23 +0200 Subject: [PATCH] Fix excessive loading of the model notes from the server --- .../ctbrec/notes/RemoteModelNotesService.java | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/common/src/main/java/ctbrec/notes/RemoteModelNotesService.java b/common/src/main/java/ctbrec/notes/RemoteModelNotesService.java index 02d26b82..8520fbee 100644 --- a/common/src/main/java/ctbrec/notes/RemoteModelNotesService.java +++ b/common/src/main/java/ctbrec/notes/RemoteModelNotesService.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.time.Instant; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -32,6 +33,9 @@ public class RemoteModelNotesService extends RemoteService implements ModelNotes private final HttpClient httpClient; private final Config config; + private Map notesCache = Collections.emptyMap(); + private Instant lastUpdate = Instant.EPOCH; + private final LoadingCache cache = CacheBuilder.newBuilder() .expireAfterWrite(3, TimeUnit.SECONDS) .maximumSize(10000) @@ -67,16 +71,19 @@ public class RemoteModelNotesService extends RemoteService implements ModelNotes }); } - private String updateCache(String modelUrl) { - try { - var modelNotes = loadAllModelNotes(); - for (Map.Entry entry : modelNotes.entrySet()) { - cache.put(entry.getKey(), entry.getValue()); + private synchronized String updateCache(String modelUrl) { + if (lastUpdate.isBefore(Instant.now().minusSeconds(3))) { + try { + notesCache = loadAllModelNotes(); + lastUpdate = Instant.now(); + for (Map.Entry entry : notesCache.entrySet()) { + cache.put(entry.getKey(), entry.getValue()); + } + } catch (Exception e) { + throw new CacheLoader.InvalidCacheLoadException("Loading of model notes from server failed"); } - return modelNotes.get(modelUrl); - } catch (Exception e) { - throw new CacheLoader.InvalidCacheLoadException("Loading of model notes from server failed"); } + return Optional.ofNullable(notesCache.get(modelUrl)).orElse(""); } @Override @@ -108,7 +115,7 @@ public class RemoteModelNotesService extends RemoteService implements ModelNotes public Optional loadModelNotes(String modelUrl) throws IOException { try { log.trace("Loading model notes for {}", modelUrl); - return Optional.of(cache.get(modelUrl)); + return Optional.ofNullable(cache.get(modelUrl)); } catch (ExecutionException e) { throw new IOException(e); }