title: How does thread synchronization work in Kotlin?
body: <p>I have been experimenting with Kotlin synchronization and I do not understand from the docs on how the locking mechanism works on thread synchronization over common resources and thus attempted to write this piece of code which further complicates my understanding.</p>
  
  <pre><code>fun main() {
      val myList = mutableListOf(1)
  
      thread {
          myList.forEach {
              while (true) {
                  println("T1 : $it")
              }
          }
      }
  
      thread {
          synchronized(myList) {
              while (true) {
                  myList[0] = 9999
                  println("**********\n**********\n**********\n")
              }
          }
      }
  }
  </code></pre>
  
  <p><code>myList</code> is the common resource in question.</p>
  
  <p>The first thread is a simple read operation that I intend to keep the resource utilized in read mode. The second is another thread which requests a lock in order to modify the common resource. </p>
  
  <p>Though the first thread does not contain any synchronization, I would expect it to internally handle this so that a while a function like <code>map</code> or <code>forEach</code> is in progress over a resource, another thread should not be able to lock it otherwise the elements being iterated over may change while the <code>map</code>/<code>forEach</code> is in progress (even though that operation may be paused for a bit while another thread has a lock over it).</p>
  
  <p>The output I see instead shows that both the threads are executing in parallel. Both of them are printing the first element in the list and the stars respectively. But in the second thread, even though the stars are being printed, <code>myList[0]</code> is never set to 9999 because the first thread continues to print 1.</p>