Skip to content

Commit 7982239

Browse files
Use concurrent hash map for basketCache
Regular hashmaps are not thread-safe, which can give occasional explosions under contention. Wrap HashMaps in synchronizedMap to protect them. A future version should replace the nested keys with a complex key Fixes #73
1 parent 157b69f commit 7982239

File tree

1 file changed

+8
-6
lines changed
  • src/main/java/edu/vanderbilt/accre/laurelin

1 file changed

+8
-6
lines changed

src/main/java/edu/vanderbilt/accre/laurelin/Cache.java

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
11
package edu.vanderbilt.accre.laurelin;
22

33
import java.lang.ref.SoftReference;
4+
import java.util.Collections;
45
import java.util.HashMap;
6+
import java.util.Map;
57
import java.util.WeakHashMap;
68

79
import edu.vanderbilt.accre.laurelin.array.RawArray;
810
import edu.vanderbilt.accre.laurelin.root_proxy.ROOTFile;
911

1012
public class Cache {
11-
WeakHashMap<ROOTFile, HashMap<Long, SoftReference<RawArray>>> cache;
13+
Map<ROOTFile, Map<Long, SoftReference<RawArray>>> cache;
1214
int totalCount = 0;
1315
int hitCount = 0;
1416
int missCount = 0;
1517

1618
public Cache() {
17-
cache = new WeakHashMap<ROOTFile, HashMap<Long, SoftReference<RawArray>>>();
19+
cache = Collections.synchronizedMap(new WeakHashMap<ROOTFile, Map<Long, SoftReference<RawArray>>>());
1820
}
1921

2022
public RawArray get(ROOTFile backingFile, long offset) {
2123
totalCount += 1;
22-
HashMap<Long, SoftReference<RawArray>> fileMap = cache.get(backingFile);
24+
Map<Long, SoftReference<RawArray>> fileMap = cache.get(backingFile);
2325
if (fileMap == null) {
2426
missCount += 1;
2527
return null;
@@ -34,14 +36,14 @@ public RawArray get(ROOTFile backingFile, long offset) {
3436
}
3537

3638
public RawArray put(ROOTFile backingFile, long offset, RawArray data) {
37-
HashMap<Long, SoftReference<RawArray>> fileMap = null;
39+
Map<Long, SoftReference<RawArray>> fileMap = null;
3840
while (fileMap == null) {
3941
fileMap = cache.get(backingFile);
4042
if (fileMap == null) {
41-
cache.putIfAbsent(backingFile, new HashMap<Long, SoftReference<RawArray>>());
43+
cache.putIfAbsent(backingFile, Collections.synchronizedMap(new HashMap<Long, SoftReference<RawArray>>()));
4244
}
4345
}
4446
fileMap.put(offset, new SoftReference<RawArray>(data));
4547
return data;
4648
}
47-
}
49+
}

0 commit comments

Comments
 (0)