https://kotlinlang.org logo
Title
l

LS

06/27/2019, 3:46 PM
is there a thread-safe version of
mutableMapOf()
? i need the map to be thread-safe, and also hold its entries in the order of insertion.
k

karelpeeters

06/27/2019, 3:49 PM
Collections.synchronizedMap(LinkedHashMap())
👍 3
Will get you some barebones thread safety.
l

LS

06/27/2019, 3:49 PM
thank you!
k

karelpeeters

06/27/2019, 3:50 PM
But keep in mind that you need to be very careful, eg doing things like
if (x in map) println(map[x])
is still thead-unsafe.
l

LS

06/27/2019, 3:51 PM
I see. thanks
b

bbaldino

06/27/2019, 4:17 PM
is it ever better to use
Collections.synchronizedMap(LinkedHashMap())
over
ConcurrentHashMap
?
k

karelpeeters

06/27/2019, 4:20 PM
If you want insertion order to be kept, otherwise no,
ConcurrentHashMap
is way better.
synchronizedMap
just naively puts a single lock on everything,
ConcurrentHashMap
actually allows things like overlapping reads etc.
b

bbaldino

06/27/2019, 4:21 PM
ah right, i guess synchronizedMap can be used on any map type (like Linked) which could be nice if you don't mind the naive synchronization