微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多线程 – 有没有greenDAO线程安全最佳实践?

我已经和 greenDAO一起去了,到目前为止这都很好.文档或网站(或任何地方)()中似乎没有涵盖的一件事情是如何处理线程安全.

我知道其他地方提到的基础知识,例如“使用单个dao会话”(Android sqlite的一般做法),我也很了解Java内存模型.图书馆内部甚至显得线程安全,或者至少是用这个意图来构建的.但是我看不到什么涵盖了这一点:

greenDAO认缓存实体.这对于完全单线程的程序是非常好的 – 对大多数用途来说,透明度和大量性能提升.但是,如果我例如loadAll()然后修改其中一个元素,我在整个应用程序中全局修改一个对象.如果我在主线程上使用它(例如显示),并且更新背景线程上的DB(正确和正确),除非特别小心,否则有明显的线程问题.

greenDAO是否在“引擎盖”下做任何事情,以防止常见的应用程序级线程问题?例如,在UI线程中修改缓存的实体,同时将其保存在后台线程中(更好地希望他们不会交错!特别是在修改列表时)有没有任何“最佳做法”来保护他们,除了一般的线程安全问题(即greenDAO期望和运作良好)?还是从多线程应用程序安全的角度来看,整个缓存是否有致命的缺陷?

解决方法

我没有greenDAO的经验,但文档在这里
http://greendao-orm.com/documentation/queries/

说:

If you use queries in multiple threads,you must call forCurrentThread() on the query to get a Query instance for the current thread. Starting with greenDAO 1.3,object instances of Query are bound to their owning thread that build the query. This lets you safely set parameters on the Query object while other threads cannot interfere. If other threads try to set parameters on the query or execute the query bound to another thread,an exception will be thrown. Like this,you don’t need a synchronized statement. In fact you should avoid locking because this may lead to deadlocks if concurrent transactions use the same Query object.

To avoid those potential deadlocks completely,greenDAO 1.3 introduced the method forCurrentThread(). This will return a thread-local instance of the Query,which is safe to use in the current thread. Every time,forCurrentThread() is called,the parameters are set to the initial parameters at the time the query was built using its builder.

尽管我可以看到文档没有明确说明多线程,除了这一点,这似乎很清楚它被处理.这正在谈论使用相同的Query对象的多个线程,所以很明显,多个线程可以访问同一个数据库.当然,数据库和DAO处理并发访问是正常的,在这种情况下,有很多成熟的技术可以用于缓存.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐