Group Group Group Group Group Group Group Group Group

Error while running this code from Chapter 11 (Channels)

I am running the code but I am having this output

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.runBlocking

@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
fun main() {

  val fruitArray = arrayOf("Apple", "Banana", "Pear", "Grapes", "Strawberry")

  fun produceFruits() = GlobalScope.produce<String> {
    for (fruit in fruitArray) {
      send(fruit)

      // Conditional close
      if (fruit == "Pear") {
        // Signal that closure of channel
        close()
      }
    }
  }

  runBlocking {
    val fruits = produceFruits()
    fruits.consumeEach { println(it) }
    println("Done!")
  }
}


Apple
Banana
Pear
Exception in thread "DefaultDispatcher-worker-1" kotlinx.coroutines.channels.ClosedSendChannelException: Channel was closed
	at kotlinx.coroutines.channels.Closed.getSendException(AbstractChannel.kt:1048)
	at kotlinx.coroutines.channels.AbstractSendChannel.offer(AbstractChannel.kt:166)
	at kotlinx.coroutines.channels.AbstractSendChannel.send(AbstractChannel.kt:146)
	at kotlinx.coroutines.channels.ChannelCoroutine.send$suspendImpl(ChannelCoroutine.kt)
	at kotlinx.coroutines.channels.ChannelCoroutine.send(ChannelCoroutine.kt)
	at com.raywenderlich.channels.ChannelIntroWithProduceKt$main$1$1.invokeSuspend(ChannelIntroWithProduce.kt:18)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:740)
Done!

Process finished with exit code 0

This does not happen always. If I run this program 10 times, it might happen one time. Can someone explain why this might be happening?

Actually, I did not copy-paste this code. I wrote the code myself after looking at the tutorial and it crashed straight away. I ran it couple of times and it succeed sometimes and failed other times. So I tried running the code from book and I got the above output.