title: Kotlin - How to lock a collection when accessing it from two threads
body: <p>wondered if anyone could assist, I'm trying to understand the correct way to access a collection in Kotlin with two threads.</p>
  
  <p>The code below simulates a problem I'm having in a live system. One thread iterates over the collection but another thread can remove elements in that array.</p>
  
  <p>I have tried adding @synchronized to the collections getter but that still gives me a concurrentmodification exception.</p>
  
  <p>Can anyone let me know what the correct way of doing this would be?</p>
  
  <pre><code>class ListTest() {
  
      val myList = mutableListOf&lt;String&gt;()
          @Synchronized
          get() = field
  
      init {
          repeat(10000) {
              myList.add("stuff: $it")
          }
      }
  }
  
  fun main() = runBlocking&lt;Unit&gt; {
  
      val listTest = ListTest()
  
      launch(Dispatchers.Default) {
          delay(1L)
          listTest.myList.remove("stuff: 54")
      }
  
      launch {
          listTest.myList.forEach { println(it) }
      }
  }
  </code></pre>