https://kotlinlang.org logo
Title
s

Storozh Kateryna

12/22/2021, 1:03 PM
Hi all! Does anybody know if synchronized works in that way with coroutines? Could it occur any problems when I get data from map in UI thread? suspend fun loadData() { val data = getDataFromDB() data?.let { updateData(it) } } @Synchronized private fun updateData(data: Map<String, Data>) { map.clear() map.putAll(data) } @Synchronized fun getData(key: String): Data? { return map[key] }
m

mkrussel

12/22/2021, 1:31 PM
It will work, since those functions are not suspending. The problem is that
loadData
is now blocking instead of suspending.
j

Joakim Forslund

12/22/2021, 1:34 PM
Is there a specific reason why you can't use coroutine Mutex?
and the helper function mutex.withLock{...} ?
s

Storozh Kateryna

12/22/2021, 1:43 PM
@Joakim Forslund The reason why I do not use mutex is because I do not need coroutines in getData function. With mutex it will be something like return runBlocking { mutex.withLock { map[key] } } right?
@mkrussel I think that updateData() does not block for a long period of time
m

mkrussel

12/22/2021, 2:14 PM
You would not use
runBlocking
, that would defeat the point of using
Mutex
instead of
Synchronized
. The mutex will suspend until it has access. If this is on a JVM another option would be to use a
ConcurrentHashMap
to avoid needed to synchronize.
s

Storozh Kateryna

12/22/2021, 2:29 PM
From what I've read in the documentation about ConcurrentHashMap "all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access" and I need to update the whole map with new data, so I think I can not use ConcurrentHashMap for synchronization here.
j

Joakim Forslund

12/22/2021, 3:43 PM
I do not understand the need to mix the two paradigms, why can't the other methods be suspend?
Generally it is not a very good idea to mix the two because the risc of getting interleaved calls
s

Storozh Kateryna

12/22/2021, 4:35 PM
So the thing is that I need to get data from this map in an application where I do not use coroutines at all and do not have coroutine scope in the main thread. So this is why this method should not be suspended. But this map can be updated with new data in another thread with data from the database or network. So it seems like a pretty easy task but I do not get how to organize it in the right way.
j

Joakim Forslund

12/22/2021, 4:47 PM
I'm afraid you are already mixing it since something has to call the suspend function. At any case, the gist of what you are doing is gonna work
s

Storozh Kateryna

12/22/2021, 4:56 PM
anyway, I hope there won't be any deadlocks or anything like that🙂, thanks for advices and your time!