Good morning/day/evening. I need a solution for th...
# coroutines
d
Good morning/day/evening. I need a solution for the following case: There is a cache, and I need to get objects from different threads (rest controller). If there is no object in cache I need to fetch this object via network. So the problem - only single thread should execute the network request, but others should wait until object is fetched and cached. This is the solution I have in mind. Is it okay?
u
No it’s not 😞 Just drop the double checking. It’s not worth it https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html TLTR: There is nothing that guarantees, that the first check will see the effect of
fastPutIfAbsent
unless there is something in
sitePositionsCache
that we can not see
d
Oh, great article, Thank you! But it's about Java's threads, but as coroutines work in a bit different way. it's not a problem to remove double check and put mutex for the whole method, but I did some tests today with this code, and it seems working.
u
Coroutines dispatch to threads
The only relevant difference is when a single coroutine jumps threads (eg by`withContext`) the coroutine machinery will put in memory barriers to make it behave like single threaded code. But if you have multiple coroutines dispatched on multiple threads the same memory model applies.
m
why not just manipulate the cache on the main thread, and then you don’t need this lock mechanic. From the code you provided, repeated networks call don’t seem to be a problem