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?
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
uli
03/18/2021, 7:24 PM
Coroutines dispatch to threads
uli
03/18/2021, 8:59 PM
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
myanmarking
03/19/2021, 12:51 PM
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