Coding in Kotlin, want a thread-safe List as described here: java concurrent Array List access
It seems Collections.kt does not have this function. Are Kotlin's mutable lists already threadsafe ? If not, how do I accomplish this ?
Thanks.
There is no thread-safety guarantee for the collections returned by mutableMapOf ( MutableMap ), mutableListOf ( MutableList ), or mutableSetOf ( MutableSet ).
A MessageService object is effectively immutable since its state can't change after its construction. So, it's thread-safe. Moreover, if MessageService were actually mutable, but multiple threads only have read-only access to it, it's thread-safe as well.
The synchronizedList() method of java. util. Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
If I try to use the Java List a warning message comes up "This class shouldn't be used in Kotlin..."
Java lists (and other collections) are mapped types in Kotlin. So you can use Collections.synchronizedList
, and it takes and returns a Kotlin List
or MutableList
.
OTOH, synchronizedList
is rarely what you actually want: it works for single method calls, but anything else must be synchronized manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With