1 /*
2  * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 // This file was automatically generated from cancellation-and-timeouts.md by Knit tool. Do not edit.
6 package kotlinx.coroutines.guide.exampleCancel09
7 
8 import kotlinx.coroutines.*
9 
10 var acquired = 0
11 
12 class Resource {
13     init { acquired++ } // Acquire the resource
closenull14     fun close() { acquired-- } // Release the resource
15 }
16 
mainnull17 fun main() {
18     runBlocking {
19         repeat(100_000) { // Launch 100K coroutines
20             launch {
21                 var resource: Resource? = null // Not acquired yet
22                 try {
23                     withTimeout(60) { // Timeout of 60 ms
24                         delay(50) // Delay for 50 ms
25                         resource = Resource() // Store a resource to the variable if acquired
26                     }
27                     // We can do something else with the resource here
28                 } finally {
29                     resource?.close() // Release the resource if it was acquired
30                 }
31             }
32         }
33     }
34     // Outside of runBlocking all coroutines have completed
35     println(acquired) // Print the number of resources still acquired
36 }
37