Are there greenDAO thread safety best practices?

后端 未结 2 1707
野的像风
野的像风 2021-02-12 17:50

I\'m having a go with greenDAO and so far it\'s going pretty well. One thing that doesn\'t seem to be covered by the docs or website (or anywhere :( ) is how it handles thread

相关标签:
2条回答
  • 2021-02-12 18:01

    I've no experience with greenDAO but the documentation here: http://greendao-orm.com/documentation/queries/

    Says:

    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.

    While so far as I can see the documentation doesn't explicitly say anything about multi threading other than this this seems pretty clear that it is handled. This is talking about multiple threads using the same Query object, so clearly multiple threads can access the same database. Certainly it's normal for databases and DAO to handle concurrent access and there are a lot of proven techniques for working with caches in this situation.

    0 讨论(0)
  • 2021-02-12 18:15

    By default GreenDAO caches and returns cached entity instances to improve performance. To prevent this behaviour, you need to call:

    daoSession.clear()

    to clear all cached instances. Alternatively you can call:

    objectDao.detachAll()

    to clear cached instances only for the specific DAO object.

    You will need to call these methods every time you want to clear the cached instances, so if you want to disable all caching, I recommend calling them in your Session or DAO accessor methods.

    • Documentation: http://greenrobot.org/greendao/documentation/sessions/#Clear_the_identity_scope
    • Discussion: https://github.com/greenrobot/greenDAO/issues/776
    0 讨论(0)
提交回复
热议问题