Consider the following code in Kotlin:
private val mLock = "lock"
suspend fun doJob(): String {
synchronized(mLock) {
if (someBoolean1) {
return "A"
}
if (someBoolean2) {
return@synchronized "B"
}
return@synchronized "C"
}
return "D"
}
Will the single return "A", that exits the doJob function from within the synchronized block, finish the synchronized block correctly? Could there be any issues with a set up like that one?
Yes
Yes, you will never return "B" or "C", only "A" or "D" since you're returning that value to the synchronized block, which is lost since it is never assigned anywhere or returned.
Also note you're unnecessarily creating a new string with
where
is enough.
Also maybe consider
@Synchronizedinstead of manually creating your lock if it's not shared among other functions.And lastly, you don't need to mark the function
suspendto usesynchronized(or@Synchronized)