2011-08-17 46 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); 
}