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

Erik

02/26/2021, 6:47 PM
I have an
object
with private construct-once properties (e.g.
private val x = SomeConstructor()
) and public
suspend
functions that access these properties. The suspending funs all use
withContext(myContext) {}
to ensure they access the properties from the correct thread. How can I ensure that the properties are instantiated on that same thread? Would it be enough to use
private val x by lazy { SomeConstructor() }
as long as
x
is only accessed from within
withContext(myContext)
? Will that guarantee that
x
is constructed on the thread(s) backing
myContext
?
m

myungpyo.shim

02/27/2021, 6:53 AM
IMHO, If you want to confine the variable to a particular thread, you can use ThreadLocal<T> with lazy delegation for the variable. In this case, I assume you use single-threaded dispatcher as the coroutine context element. If you use multi-threaded dispatcher (e.g. Dispatchers.IO, Dispatchers.Default, ...) as context element, the variable could be changed as the coroutine is resumed on the different worker thread in the pool. (As you may know, you can confine the variable to a coroutine scope using ThreadLocal<T>.asContextElement(). But I think this is not the thing you wanted to know.) (I've googled with the keywords "ThreadLocal" and "lazy delegation" and found Someone answered the delegation sample. Could help you. https://stackoverflow.com/questions/45970738/kotlin-delegate-property-by-lazy-that-is-thread-local)
e

Erik

02/27/2021, 7:06 AM
Thanks. That would work as well. However, I'm not looking too have an instance per thread, but just one instance for my single threaded context. Still, that can be done with your approach or the SO Q&A that you linked to.
😀 1
5 Views