安卓LruCache(安卓3.1),线程安全 [英] Android LruCache (Android 3.1) thread safety

查看:182
本文介绍了安卓LruCache(安卓3.1),线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是全新的Andr​​oid类 LruCache 线程安全的? Java的医生说:

  

这个类是线程安全的。

:由原子上的缓存同步执行多个缓存操作

 同步(缓存){
     如果(cache.get(键)== NULL){
         cache.put(键,值);

   }}
 

难道他们的意思是说不是线程安全的?为什么总会有必须同步,如果类是线程安全的吗?

谢谢!

解决方案

没关系的类是否是线程安全与否。如果使用多个操作,你可能仍然需要同步。取决于你如何使用它。

 如果(cache.get(键)== NULL)
{
  //在这一点上,你认为有没有这样的价值在缓存中
  //但另一个线程可能刚刚增加了一个执行之间
  //这两行的code
  cache.put(键,值);
}
 

Is the new Android class LruCache thread safe? The java doc says:

This class is thread-safe. Perform multiple cache operations atomically by synchronizing on the cache:

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

   }}

Did they mean to say NOT thread-safe? Why would one have to synchronize if the class is thread safe?

Thanks!

解决方案

Doesn't matter whether the class is thread-safe or not. If you use multiple operations you may still need to synchronize. Depends on how you use it.

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

这篇关于安卓LruCache(安卓3.1),线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆