I need to cache the least recent result (say 10,000) of a concurrent system, and random access them. Since most of concurrent cache are based on linked list, I'm wondering if there is a thread safe random access circular array in java?
-
Can you give more details on how you need to use it? In example, could Guava's in-memory cache work for you?Daniele– Daniele2020-03-08 17:08:34 +00:00Commented Mar 8, 2020 at 17:08
-
Assuming by "random access" you mean access by index? If so, is it by LRU order? If so, why do you need that? What are you actually trying to achieve?Bohemian– Bohemian ♦2020-03-08 18:08:24 +00:00Commented Mar 8, 2020 at 18:08
-
@Daniele Local cache for fail over, write operation is much more than readlos– los2020-03-09 06:07:12 +00:00Commented Mar 9, 2020 at 6:07
-
@Bohemian Yes, by index, but restriction is weaker than LRU, cause it's only used for failoverlos– los2020-03-09 06:11:59 +00:00Commented Mar 9, 2020 at 6:11
-
1The locking issues of a linked list shouldn't be a problem in a well designed cache. If you need LRU then ConcurrentLinkedHashMap or Guava's Cache should suffice. If you can leverage a smarter eviction policy, then Caffeine is preferrable. See benchmarks.Ben Manes– Ben Manes2020-03-09 06:20:20 +00:00Commented Mar 9, 2020 at 6:20
2 Answers
For caches without timeout, I often use the ConcurrentHashMap. You may also take a look at the CopyOnWriteArrayList.
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html
2 Comments
List<String> list = Collections.synchronizedList(new ArrayList<String>()); There is an implementation of CircularFifoQueue in the Apache Commons Collections library. It contains a get() method for random access. For a thread-safe version, you can wrap its instance with the SynchronizedQueue wrapper. Another solution is the cyclic ArrayList/Vector implementation, described in detail here.