Skip to content

Mutex.withLock() added EXACTLY_ONCE contract #2010

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

Merged

Conversation

ZhouGongZaiShi
Copy link
Contributor

Mutex.withLock(owner: Any? = null, action: () -> T) should be like synchronized (lock: Any, block:()-> R), add EXACTLY_ONCE contract.
This is very helpful when the compiler infers variable initialization.

val str : String
mMutex.withLock {
   str = "If no Exception is thrown, it will be assigned."
}
println("I should be able to use str field. str = $str")

@fvasco
Copy link
Contributor

fvasco commented May 11, 2020

Same issue on Semaphore.withPermit

@zach-klippenstein
Copy link
Contributor

I think this needs to be AT_MOST_ONCE since the block won't be ran at all if lock throws (eg cancelled while suspended).

@ZhouGongZaiShi
Copy link
Contributor Author

I think this needs to be AT_MOST_ONCE since the block won't be ran at all if lock throws (eg cancelled while suspended).

I think that if mutex.withlock{} throws a CancellationException(or other exception) while suspended, then the coroutine will not run the code after mutex.withlock{}.

@zach-klippenstein
Copy link
Contributor

Yep, I forgot that the compiler will assume anything run inside a try wasn't executed if it throws.

Copy link
Contributor

@elizarov elizarov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, but let's also add a similar contract on Semaphore.withPermit in the same PR for consistency.

Copy link
Contributor

@elizarov elizarov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to go now. Waiting for tests to pass.

@qwwdfsad qwwdfsad changed the base branch from master to develop May 15, 2020 09:26
@qwwdfsad qwwdfsad merged commit e470df9 into Kotlin:develop May 15, 2020
recheej pushed a commit to recheej/kotlinx.coroutines that referenced this pull request Dec 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants