2011-08-17 33 views
11

新安卓类LruCache线程安全吗? java的医生说:Android LruCache(Android 3.1)线程安全

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

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

    }} 

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

谢谢!

回答

17

不要紧类是线程安全与否。如果您使用多个操作,则可能仍需要同步。取决于你如何使用它。

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