2011-08-17 13 views
11

La nuova classe Android LruCache thread è sicura? Il documento java dice:Sicurezza threading Android LruCache (Android 3.1)

Questa classe è thread-safe. Eseguire più operazioni di cache in modo atomico sincronizzando sulla cache:

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

    }} 

intendevano dire che non thread-safe? Perché dovremmo sincronizzarci se la classe è thread-safe?

Grazie!

risposta

17

Non importa se la classe è sicura per i thread o meno. Se si utilizzano più operazioni, potrebbe essere necessario sincronizzarsi. Dipende da come lo si usa.

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