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.

Share:
22,128

Related videos on Youtube

A.Sanchez.SD
Author by

A.Sanchez.SD

Updated on May 31, 2020

Comments

  • A.Sanchez.SD
    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
      Shadov almost 6 years
      Why 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
      shmosel almost 6 years
      @Shadov I don't think Kotlin's collection library is interoperable with the JDK's.
    • A.Sanchez.SD
      A.Sanchez.SD almost 6 years
      If 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
      Alexey Romanov almost 6 years
    • shmosel
      shmosel almost 6 years
      @AlexeyRomanov Interesting. So does that mean you can actually use the Collections wrappers?
    • Alexey Romanov
      Alexey Romanov almost 6 years
      @shmosel Yes (in a JVM-only project, of course).
  • milosmns
    milosmns over 5 years
    Right, 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
    IgorGanapolsky about 3 years
    So there is no completely synchronized collection in Kotlin right now?
  • Alexey Romanov
    Alexey Romanov about 3 years
    As 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
    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. So Collections.synchronizedList should work fine docs.oracle.com/javase/8/docs/api/java/util/…
  • milosmns
    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 :)