Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Kotlin equivalent of Java's Collections.synchronizedList ? Or is this not needed in Kotlin

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.

like image 514
A.Sanchez.SD Avatar asked May 30 '18 22:05

A.Sanchez.SD


People also ask

Is Kotlin MutableSet thread-safe?

There is no thread-safety guarantee for the collections returned by mutableMapOf ( MutableMap ), mutableListOf ( MutableList ), or mutableSetOf ( MutableSet ).

What is thread safety in Kotlin?

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.

What is collections synchronizedList?

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.


1 Answers

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.

like image 107
Alexey Romanov Avatar answered Sep 20 '22 11:09

Alexey Romanov