Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android LruCache (Android 3.1) thread safety

Is the new Android class LruCache thread safe? The java doc says:

This class is thread-safe. Perform multiple cache operations atomically by synchronizing on the cache:

   synchronized (cache) {
     if (cache.get(key) == null) {
         cache.put(key, value);

   }}

Did they mean to say NOT thread-safe? Why would one have to synchronize if the class is thread safe?

Thanks!

like image 857
dnkoutso Avatar asked Aug 17 '11 00:08

dnkoutso


People also ask

Is LRU cache thread safe?

lru. LRU is not thread-safe; session cache maintenance (web3.

What is LRU cache in android?

android.util.LruCache. A cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.

How do you use LruCache?

One way to implement an LRU cache in Python is to use a combination of a doubly linked list and a hash map. The head element of the doubly linked list would point to the most recently used entry, and the tail would point to the least recently used entry.

How would a LRU cache work on a single machine which is multi threaded?

A simple LRU Cache implementation uses a doubly linked list; adding new items to the head, removing items from the tail, and moving any existing items to the head when referenced (touched). This algorithm is good for single threaded applications but becomes very slow in a multi-threaded environment.


1 Answers

Doesn't matter whether the class is thread-safe or not. If you use multiple operations you may still need to synchronize. Depends on how you use it.

if (cache.get(key) == null)
{
  //at this point you think there is no such value in the cache
  //but another thread might have just added one between executing
  //those two lines of code
  cache.put(key, value);
}
like image 56
mibollma Avatar answered Sep 29 '22 10:09

mibollma