Android LruCache (Android 3.1) thread safety
Asked Answered
C

1

12

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!

Cuttlebone answered 17/8, 2011 at 0:40 Comment(0)
K
18

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);
}
Klinger answered 17/8, 2011 at 0:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.