xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-core/jvm/test/guide/example-cancel-10.kt (revision 7a7160fed73afa6648ef8aa100d4a336fe921d9a)
1 // This file was automatically generated from cancellation-and-timeouts.md by Knit tool. Do not edit.
2 package kotlinx.coroutines.guide.exampleCancel10
3 
4 import kotlinx.coroutines.*
5 
6 var acquired = 0
7 
8 class Resource {
9     init { acquired++ } // Acquire the resource
closenull10     fun close() { acquired-- } // Release the resource
11 }
12 
mainnull13 fun main() {
14     runBlocking {
15         repeat(10_000) { // Launch 10K coroutines
16             launch {
17                 var resource: Resource? = null // Not acquired yet
18                 try {
19                     withTimeout(60) { // Timeout of 60 ms
20                         delay(50) // Delay for 50 ms
21                         resource = Resource() // Store a resource to the variable if acquired
22                     }
23                     // We can do something else with the resource here
24                 } finally {
25                     resource?.close() // Release the resource if it was acquired
26                 }
27             }
28         }
29     }
30     // Outside of runBlocking all coroutines have completed
31     println(acquired) // Print the number of resources still acquired
32 }
33