Kotlin synchronized returning to outer function causes issues

275 views Asked by At

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?

1

There are 1 answers

1
m0skit0 On

Will the single return "A", that exits the doJob function from within the synchronized block, finish the synchronized block correctly?

Yes

Could there be any issues with a set up like that one?

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

private val mLock = "lock"

where

private val lock = Any()

is enough.

Also maybe consider @Synchronized instead of manually creating your lock if it's not shared among other functions.

And lastly, you don't need to mark the function suspend to use synchronized (or @Synchronized)