Search code examples
androidthread-safetylru

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!


Solution

  • 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);
    }