Roman Elizarov | 20ca97a | 2020-10-08 17:16:40 +0300 | [diff] [blame] | 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.exampleCancel08 |
| 7 | |
| 8 | import kotlinx.coroutines.* |
| 9 | |
| 10 | var acquired = 0 |
| 11 | |
| 12 | class Resource { |
| 13 | init { acquired++ } // Acquire the resource |
| 14 | fun close() { acquired-- } // Release the resource |
| 15 | } |
| 16 | |
| 17 | fun main() { |
| 18 | runBlocking { |
| 19 | repeat(100_000) { // Launch 100K coroutines |
| 20 | launch { |
| 21 | val resource = withTimeout(60) { // Timeout of 60 ms |
| 22 | delay(50) // Delay for 50 ms |
| 23 | Resource() // Acquire a resource and return it from withTimeout block |
| 24 | } |
| 25 | resource.close() // Release the resource |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | // Outside of runBlocking all coroutines have completed |
| 30 | println(acquired) // Print the number of resources still acquired |
| 31 | } |