0

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?

13
  • Can you give more details on how you need to use it? In example, could Guava's in-memory cache work for you? Commented 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? Commented Mar 8, 2020 at 18:08
  • @Daniele Local cache for fail over, write operation is much more than read Commented Mar 9, 2020 at 6:07
  • @Bohemian Yes, by index, but restriction is weaker than LRU, cause it's only used for failover Commented Mar 9, 2020 at 6:11
  • 1
    The 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. Commented Mar 9, 2020 at 6:20

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

According to the document, copyOnWriteArrayList is more efficient when traversal operations vastly outnumber mutations. But we have much more write than read
Then you may use a traditional array and synchronize access to it: List<String> list = Collections.synchronizedList(new ArrayList<String>());
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.