arrow icon indicating copy to clipboard operation
arrow copied to clipboard

["Bug"] Deadlock when trying to create Either.Left(Unit) and Either.Right(null) concurrently

Open ilya40umov opened this issue 5 years ago • 10 comments

Arrow version: 0.13.1 Coroutines version: 1.4.3

The following code hangs and never finished on 0.13.1 (I discovered this while trying to update Arrow from 0.11.0 and one of my tests that involves concurrency failed).

fun main() {
    runBlocking {
        (0..10).map { i ->
            GlobalScope.launch {
                println("Before")
                if (i % 2 == 0) {
                    Either.Left(Unit)
                } else {
                    Either.Right(null)
                }
                println("After") // never gets printed
            }
        }.joinAll()
    }
}

Here is a thread dump from some of the threads:

"DefaultDispatcher-worker-7" #19 daemon prio=5 os_prio=0 cpu=1.03ms elapsed=282.59s tid=0x00007f7b1c5ce800 nid=0x1a37da in Object.wait()  [0x00007f7acea01000]
   java.lang.Thread.State: RUNNABLE
	at arrow.core.Either.<clinit>(Either.kt:945)
	at MainKt$main$1$1$1.invokeSuspend(main.kt:13)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

"DefaultDispatcher-worker-1" #13 daemon prio=5 os_prio=0 cpu=1.05ms elapsed=282.59s tid=0x00007f7b1c543000 nid=0x1a37d4 in Object.wait()  [0x00007f7acf008000]
   java.lang.Thread.State: RUNNABLE
	at MainKt$main$1$1$1.invokeSuspend(main.kt:13)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

"DefaultDispatcher-worker-2" #14 daemon prio=5 os_prio=0 cpu=0.44ms elapsed=282.59s tid=0x00007f7b1c5dc000 nid=0x1a37d5 in Object.wait()  [0x00007f7acef07000]
   java.lang.Thread.State: RUNNABLE
	at MainKt$main$1$1$1.invokeSuspend(main.kt:15)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

ilya40umov avatar Apr 16 '21 16:04 ilya40umov

We were bitten by this problem after upgrading to 0.13.x as well. I haven't looked into the details yet but it seems related to the initialization of the companion objects in Either, Either.Right, and Either.Left. We skipped version 0.12 but version 0.13, different than version 0.11, defines Left and Right as inner classes of Either.

A quick work around is to evaluate the Either companion object prior to launching the coroutines. Say, println(Either).

dberg avatar Apr 20 '21 02:04 dberg

It feels like a bug with coroutines rather than with Either. As Simon said on Slack, there's no synchronization involved other that whatever Kotlin has for objects.

https://github.com/arrow-kt/arrow/blob/1d2771f057d398115823e882e066b8c654a68711/arrow-libs/core/arrow-core/src/main/kotlin/arrow/core/Either.kt#L908-L927

pakoito avatar Apr 20 '21 12:04 pakoito

The following code has the same behavior, so I don't think it's a coroutines-specific problem.

import arrow.core.Either
import java.util.concurrent.Executors

fun main() {
    val executor = Executors.newFixedThreadPool(10)
    (0..10).map { i ->
        executor.submit {
            println("Before")
            if (i % 2 == 0) {
                Either.Left(Unit)
            } else {
                Either.Right(null)
            }
            println("After")
        }
    }.forEach { it.get() }
    executor.shutdown()
}

ilya40umov avatar Apr 20 '21 12:04 ilya40umov

there's no synchronization involved other that whatever Kotlin has for objects.

Yeah, looks like the issue is indeed caused by the synchronization that Kotlin adds for objects. However, since Arrow is now relying on those, I would like to know if it's possible to solve on the library level.

ilya40umov avatar Apr 20 '21 12:04 ilya40umov

BTW, I also believe the issue is with the companion object (take a look at the thread dump I originally posted - one of the threads is stuck in internal val unit: Either<Nothing, Unit> = Right(Unit)):

companion object {

    @PublishedApi
    internal val leftUnit: Either<Unit, Nothing> =
      Left(Unit)

    @PublishedApi
    internal val unit: Either<Nothing, Unit> = Right(Unit)
...
}

ilya40umov avatar Apr 20 '21 12:04 ilya40umov

I was able to quickly reproduce the issue with a custom Either class, the culprit is exactly what @ilya40umov posted, the internal vals seem to be causing the issue, most likely because they're being initialized eagerly at the very moment someone first calls any Either class function or constructor, so if it's the first call to either in the entire app, this happens.

You can try it out by simply adding an Either mention right before the code:

fun main() {
    Either // <-- this mention makes Either initialize it's internal companion properties, so the code below don't hang anymore
    runBlocking {
        (0..10).map { i ->
            GlobalScope.launch {
                println("Before")
                if (i % 2 == 0) {
                    Either.Left(Unit)
                } else {
                    Either.Right(null)
                }
                println("After") // never gets printed
            }
        }.joinAll()
    }
}

A quick fix could be:

    @PublishedApi
    internal val leftUnit: Either<Unit, Nothing> by lazy { Left(Unit) }

    @PublishedApi
    internal val unit: Either<Nothing, Unit> by lazy { Right(Unit) }

aballano avatar Apr 20 '21 13:04 aballano

🤯

Since these are internal I think we can also remove it from the companion and move it somewhere else. If we'd move these functions to the their respective Either.Left and Either.Right companion object then it wouldn't cause any issue anymore, would it?

nomisRev avatar Apr 20 '21 13:04 nomisRev

Agreed, that might fix the issue. The root of the problem seems related to having a static variable in the super class referencing its subclass and the classloader deadlocking.

Either {
   private static final Either leftUnit;
   private static final Either unit;

   static {
      leftUnit = (Either)(new Either.Left(Unit.INSTANCE));
      unit = (Either)(new Either.Right(Unit.INSTANCE));
   }
}

The kotlin compiler could probably issue a warning in such cases as well if that's indeed the problem.

dberg avatar Apr 20 '21 14:04 dberg

I think Validated has the same problem. I ran a quick test to confirm. The culprit should the static variable unit

Validated {
    companion object {
        @PublishedApi
        internal val unit: Validated<Nothing, Unit> = Validated.Valid(Unit)
    }
}

dberg avatar Apr 21 '21 00:04 dberg

Closed by #2377, thank you a lot @ilya40umov for your contribution!! 🎉

aballano avatar Apr 23 '21 20:04 aballano