https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Thomas

05/16/2019, 5:58 PM
I have a class which is not allowed to access certain objects from multiple threads. (Similar to a database). The function
newSingleThreadContext
should do what I want but that creates its own thread pool, which will cause unnecessary thread switching. The doc links to issue #261. Is there an update on that issue?
e

elizarov

05/16/2019, 7:34 PM
It is thread-confined (you have to to use it from one specific thread because it maybe uses thread-locals internally or otherwise remembers an explicit reference to a thread somewhere) or is just not thread-safe as most regular data-structures are (you cannot use it concurrently from two threads, but using it from one thread, then sequentially from another thread, is fine)?
Your "similar to database" is unfortunately of little help to understand your specific problem, as different database drivers and implementations are different w.r.t. thread-safety. For example, a typical JDBC
Connection
is usually not thread-safe but is not confined to a thread, which is used by a typical connection pool, but some C-based DB technologies (like low-level sqlite API) are often thread-confined due to thread-local data structures they internally use.
t

Thomas

05/16/2019, 9:47 PM
@elizarov thanks for explaining. What I need is something which runs sequentially (thread safe). It shouldn't matter which thread it runs, it just cannot happen concurrently.
e

elizarov

05/16/2019, 9:52 PM
Then you don't need anything special. Just make sure you access it from a single coroutine. You can read more here: https://proandroiddev.com/what-is-concurrent-access-to-mutable-state-f386e5cb8292
t

Thomas

05/17/2019, 4:06 PM
@elizarov your article is very helpful and I understand much better now. Thank you for your help!
2 Views