-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Acquiring a semaphore inside withTimeout block doesn't guarantee to release a semaphore when timed out #2233
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
It works as designed and I don't see how it could conceivably work in a different way. See, the Currently, the most portable and straightforward way to write the code you need that I can think of is:
Note, how using Does it help? |
This is a tricky gotcha that needs additional explanation. There are two examples added, one showing the bad code and explaining why it does not work, and the other showing the correct way to write it. Fixes #2233
I've created PR #2252 with a new section in the coroutines guide explaining this particular aspect of |
…in#2252) This is a tricky gotcha that needs additional explanation. There are two examples added, one showing the bad code and explaining why it does not work, and the other showing the correct way to write it. Fixes Kotlin#2233
…in#2252) This is a tricky gotcha that needs additional explanation. There are two examples added, one showing the bad code and explaining why it does not work, and the other showing the correct way to write it. Fixes Kotlin#2233
Hello! Today I have discovered a strange behavior the work of withTimeout method.
I've need a simple function like tryAcquire(long timeout, TimeUnit unit) from java.util.concurrent.Semaphore but working in a non-blocking manner. I've implemented it as an extension function to kotlinx.coroutines.sync.Semaphore class and it looks this:
When I was testing this function by code block below I encountered non-deterministic results:
Sometimes it prints 0 to my console! In other words, there're no available permits in my semaphore but 10 are expected!
I've tried to add some counters that could be useful to research this behavior, all code placed here: https://gist.github.com/akrikheli/121171b3fbca50ddad93e8b8d5b09a48
The output log when this problem is reproduced:
So, the real acquisition of the semaphore was 20 times instead of the expected 10 despite the cancellation was 4990 times (5000-10) and it's a bit confusing.
As a workaround, I can rewrite my extension function using tryAcquire method in the loop.
May be anybody can explain the current behavior when acquire method used in withTimeout block?
The text was updated successfully, but these errors were encountered: