1

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?

Damia Fuentes
  • 5,308
  • 6
  • 33
  • 65

1 Answers1

2

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)

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • 3
    Even more, we shouldn't at all use `synchronized {}` in a suspend function. If this function can be suspend, then we should use a `Mutex.withLock {}` instead. – broot Apr 21 '23 at 21:01