12

新的 Android 类LruCache线程安全吗?java文档说:

这个类是线程安全的。通过在缓存上同步来原子地执行多个缓存操作:

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

   }}

他们的意思是说不是线程安全的吗?如果类是线程安全的,为什么还要同步呢?

谢谢!

4

1 回答 1

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);
}
于 2011-08-17T00:50:04.790 回答