Is there a Kotlin equivalent of Java's Collections.synchronizedList ? Or is this not needed in Kotlin
22,128
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.
Related videos on Youtube
Author by
A.Sanchez.SD
Updated on May 31, 2020Comments
-
A.Sanchez.SD almost 4 years
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.
-
Shadov almost 6 yearsWhy not just use the Java one? It will work fine since Kotlin is completely interoperable with Java. Kotlin's mutable lists are not thread-safe.
-
shmosel almost 6 years@Shadov I don't think Kotlin's collection library is interoperable with the JDK's.
-
A.Sanchez.SD almost 6 yearsIf I try to use the Java List a warning message comes up "This class shouldn't be used in Kotlin..." Not sure if that is merely a suggestion or serious direction due to some issue...
-
Alexey Romanov almost 6 years@shmosel Yes, it is: kotlinlang.org/docs/reference/java-interop.html#mapped-types.
-
shmosel almost 6 years@AlexeyRomanov Interesting. So does that mean you can actually use the
Collections
wrappers? -
Alexey Romanov almost 6 years@shmosel Yes (in a JVM-only project, of course).
-
-
milosmns over 5 yearsRight, it doesn't really prevent
ConcurrentModificationException
, for example. You can still get it while accessing the list from two different threads using two methods/functions at the same time. -
IgorGanapolsky about 3 yearsSo there is no completely synchronized collection in Kotlin right now?
-
Alexey Romanov about 3 yearsAs far as I know it's impossible to create one, in Kotlin or in Java. It has to be specific to your project because different projects need different operations to be atomic.
-
user924 over 2 years@milosmns because you didn't read description of this method
It is imperative that the user manually synchronize on the returned list when iterating over it
. SoCollections.synchronizedList
should work fine docs.oracle.com/javase/8/docs/api/java/util/… -
milosmns over 2 years@user924 Nah, I waited 3 years for you to read it for me and point out that I didn't do it :)