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!
lru. LRU is not thread-safe; session cache maintenance (web3.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With