Are there greenDAO thread safety best practices?

后端 未结 2 1440
闹比i
闹比i 2021-02-12 17:52

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 17:56

    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.

提交回复
热议问题