Skip to content

Commit

Permalink
LruCache thread-safety with synchronization
Browse files Browse the repository at this point in the history
  • Loading branch information
d0by1 committed Jun 10, 2023
1 parent 12f2552 commit 3df0ccc
Showing 1 changed file with 16 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand All @@ -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);
}

}

0 comments on commit 3df0ccc

Please sign in to comment.