Android LruCache(Android 3.1)线程安全

dnk*_*tso 12 android thread-safety lru

新的Android类LruCache线程是否安全?java doc说:

这个类是线程安全的.通过在缓存上同步以原子方式执行多个缓存操作:

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

   }}
Run Code Online (Sandbox Code Playgroud)

他们是不是说不是线程安全的?如果类是线程安全的,为什么必须同步?

谢谢!

mib*_*lma 18

这个类是否是线程安全的并不重要.如果您使用多个操作,您可能仍需要同步.取决于你如何使用它.

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);
}
Run Code Online (Sandbox Code Playgroud)