spek icon indicating copy to clipboard operation
spek copied to clipboard

Memoized is not thread safe.

Open jcornaz opened this issue 5 years ago • 4 comments

If a memoized value is accessed concurrently by many threads in the same test, then it might create the value many times.

Example:

describe("concurrent access to memoized") {
    val obj by memoized {
        println("create")
    }

    it("test") {
        runBlocking {
            val barrier = CompletableDeferred<Unit>()

            repeat(100) {
                launch(Dispatchers.Default) {
                    barrier.await()
                    obj
                }
            }

            barrier.complete(Unit)
        }
    }
}

on my computer prints:

create
create
create
create
create
create
create
create
create
create
create

jcornaz avatar Jul 06 '19 16:07 jcornaz

This might become obselete once I make memoized eagerly evaluated.

raniejade avatar Jul 07 '19 09:07 raniejade

Encountered same problem, when will eagerly evaluated memoized be available?

RationalityFrontline avatar Nov 25 '20 03:11 RationalityFrontline

As the PR for 'eager evaluation of memoized ' has been closed (#661). Maybe memoized could be made thread safe in the mean time?

jcornaz avatar Nov 25 '20 08:11 jcornaz

In 2.1.0 memoized will be eagerly evaluated (see #835), I don't think it's a good idea to include it to in the 2.0.x line since it is a big change. I might re-scope the 2.1.0 release to just include a better IJ plugin and coroutines support, before, I wanted to add Kotlin\Native support but unfortunately the compiler plugin api is not stable enough so I guess I'll push that back.

raniejade avatar Nov 25 '20 08:11 raniejade