@@ -379,10 +379,11 @@ The timeout event in [withTimeout] is asynchronous with respect to the code runn
379
379
even right before the return from inside of the timeout block. Keep this in mind if you open or acquire some
380
380
resource inside the block that needs closing or release outside of the block.
381
381
382
- For example, here we imitate a closeable resource with the ` Resource ` class, that simply keeps track of how many times
383
- it was created by incrementing the ` acquired ` counter and decrementing this counter from its ` close ` function.
384
- Let us run a lot of coroutines with the small timeout try acquire this resource from inside
385
- of the ` withTimeout ` block after a bit of delay and release it from outside.
382
+ For example, here we imitate a closeable resource with the ` Resource ` class that simply keeps track of how many times
383
+ it was created by incrementing the ` acquired ` counter and decrementing the counter in its ` close ` function.
384
+ Now let us let us create a lot of coroutines, each of which creates a ` Resource ` at the end of the ` withTimeout ` block
385
+ and releases the resource outside the block. We add a small delay so that it is more likely that the timeout occurs
386
+ right when the ` withTimeout ` block is already finished, which will cause a resource leak.
386
387
387
388
``` kotlin
388
389
import kotlinx.coroutines.*
@@ -420,16 +421,16 @@ fun main() {
420
421
421
422
<!-- - CLEAR -->
422
423
423
- If you run the above code you'll see that it does not always print zero, though it may depend on the timings
424
- of your machine you may need to tweak timeouts in this example to actually see non-zero values.
424
+ If you run the above code, you'll see that it does not always print zero, though it may depend on the timings
425
+ of your machine. You may need to tweak the timeout in this example to actually see non-zero values.
425
426
426
- > Note that incrementing and decrementing ` acquired ` counter here from 100K coroutines is completely safe,
427
- > since it always happens from the same main thread. More on that will be explained in the chapter
428
- > on coroutine context.
427
+ > Note that incrementing and decrementing ` acquired ` counter here from 100K coroutines is completely thread- safe,
428
+ > since it always happens from the same thread, the one used by ` runBlocking ` .
429
+ > More on that will be explained in the chapter on coroutine context.
429
430
>
430
431
{type="note"}
431
432
432
- To work around this problem you can store a reference to the resource in the variable as opposed to returning it
433
+ To work around this problem you can store a reference to the resource in a variable instead of returning it
433
434
from the ` withTimeout ` block.
434
435
435
436
``` kotlin
0 commit comments