Good morning/day/evening. I need a solution for th...
# coroutines
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?
No it’s not 😞 Just drop the double checking. It’s not worth it TLTR: There is nothing that guarantees, that the first check will see the effect of
unless there is something in
that we can not see
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.
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.
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