https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

spand

09/25/2018, 12:17 PM
Trying to migrate to 1.3.0-rc-57 and 0.26.1-eap13 and I get errors for code that is basically:
Copy code
synchronized(lock){
    implicitScope.launch {
        delay(1)
    }
}
I get an error that says: " The 'delay' suspension point is inside a critical section". Seems safe to me ?
v

Vsevolod Tolstopyatov [JB]

09/25/2018, 12:33 PM
But it’s not safe. You have close to none guarantees on which thread coroutine will be resumed after delay. And it’s impossible (at least on JVM) to acquire monitor on one thread and release it on another
without this warning you’d likely to have
IllegalMonitorException
s

spand

09/25/2018, 12:37 PM
I dont expect the delay to take place on the initial thread.
Or is there another problem ?
v

Vsevolod Tolstopyatov [JB]

09/25/2018, 12:38 PM
I dont expect the delay to take place on the initial thread.
But
synchronized
machinery do, that’s why it is forbidden
s

spand

09/25/2018, 12:45 PM
I am just a bit lost as to why this is allowed:
Copy code
class Foo : CoroutineScope by GlobalScope {
    fun foo() = synchronized(Any()){
        myLaunch()
    }

    fun myLaunch(): Job = launch {
        delay(1)
    }
}
but after inlining
myLaunch
it is not. Why is it not just plain old normal blocking code?
v

Vsevolod Tolstopyatov [JB]

09/25/2018, 12:52 PM
because
myLaunch
is not suspending function and does not suspend. It just launches new task with delay and this task will be executed outside of the
syncrhonized
block
s

spand

09/25/2018, 1:02 PM
I am sorry if I am being daft, but why is that not the case in the inlined version ?
launch
is not a suspending function either. Why does the block given to
launch
have any relation to the synchronized here?
Nothing, as far as I can see, makes the assumption to be run with the lock taken in the block given to
launch
, hence I cant see why it is a problem.
u

uhe

09/25/2018, 1:24 PM
tbh that looks like a bug to me
I may decide to use normal synchronization to coordinate launching coroutines. The content of the actual launched coroutine should not matter.
s

spand

09/25/2018, 1:26 PM
I dont get it either. It is up now as https://youtrack.jetbrains.com/issue/KT-27130
v

Vsevolod Tolstopyatov [JB]

09/25/2018, 1:37 PM
oh, sorry, I’ve misunderstood you. Thanks for the report!