cats icon indicating copy to clipboard operation
cats copied to clipboard

`Eval` thread safety

Open durban opened this issue 1 year ago • 4 comments

If we have an Eval like this:

val e = Eval.defer(Eval.always { println("foo") }).memoize

Accessing e.value concurrently from different threads sometimes prints foo twice. I'm not sure if Eval is supposed to be thread safe, but this seems like a bug.

durban avatar May 07 '24 14:05 durban

Memoize isn't for effects. It should always produce the correct value but in a multithreaded environment it may be evaluated more than once.

Preventing that requires a lock during the eval evalution which would harm performance for those using it for the intended use case: controlling laziness and avoiding stack overflows.

If you care if a race can cause the eval to be run twice probably I'd use a IO or a newtype/opaque type wrapper on IO.

johnynek avatar May 07 '24 16:05 johnynek

Fair enough. I guess then the lazy val could also be removed form Later, right?

durban avatar May 08 '24 11:05 durban

If you mean we don't need the synchronization that lazy val gives then yes. We could reimplement a "evaluate once" semantic without any sychronization and it may be faster. If we had benchmarks to show that it was faster I'd support merging it.

johnynek avatar May 08 '24 16:05 johnynek

Three alternate approaches to laziness, with various tradeoffs, are exemplified in latr.

rossabaker avatar May 08 '24 16:05 rossabaker