From 3df0ccca0eccc54e85856d5d837d1c499d44e7f2 Mon Sep 17 00:00:00 2001 From: d0by Date: Sat, 10 Jun 2023 12:05:55 +0200 Subject: [PATCH] LruCache thread-safety with synchronization --- .../api/utils/color/caching/LruCache.java | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main/java/eu/decentsoftware/holograms/api/utils/color/caching/LruCache.java b/src/main/java/eu/decentsoftware/holograms/api/utils/color/caching/LruCache.java index 26d12f6a..7dd29179 100644 --- a/src/main/java/eu/decentsoftware/holograms/api/utils/color/caching/LruCache.java +++ b/src/main/java/eu/decentsoftware/holograms/api/utils/color/caching/LruCache.java @@ -28,8 +28,10 @@ public LruCache(int maxSize) { public String getResult(String input) { if (input != null && MAP.containsKey(input)) { LruElement curr = MAP.get(input); - QUE.remove(input); - QUE.addFirst(input); + synchronized (QUE) { + QUE.remove(input); + QUE.addFirst(input); + } return curr.getResult(); } @@ -40,18 +42,20 @@ public void put(String input, String result) { if (input == null || result == null) { return; } - if (MAP.containsKey(input)) { - QUE.remove(input); - } else { - int size = QUE.size(); - if (size == maxSize && size > 0) { - String temp = QUE.removeLast(); - MAP.remove(temp); + synchronized (QUE) { + if (MAP.containsKey(input)) { + QUE.remove(input); + } else { + int size = QUE.size(); + if (size == maxSize && size > 0) { + String temp = QUE.removeLast(); + MAP.remove(temp); + } } + LruElement newObj = new LruElement(input, result); + QUE.addFirst(input); + MAP.put(input, newObj); } - LruElement newObj = new LruElement(input, result); - QUE.addFirst(input); - MAP.put(input, newObj); } }