Is there any overhead of multiple coroutines waiti...
# coroutines
v
Is there any overhead of multiple coroutines waiting on same Deferred<T> (race conditions/thread safety)?
p
IIRC they’re single use so its results are cached. I don’t believe you have assured order of delivery in the order of when you awaited on them tho. Someone please correct me.
👍 1
g
Deferred is a readonly readable interface, so you can absolutely have multiple coroutines call
await()
or
select { onAwait
. I dont know if coroutines suspended on either of those methods are resumed in FIFO ordering, but if I had to guess I'd say they were, though of course if your not careful you're likely to get dispatched on the common-pool which will give you parallelism by default. The
CompletableFuture
uses a reasonably simple CAS loop to `complete`: int his way, only one
complete
(or
completeExceptionally
) call will succeed. Note the API for
complete
returns a boolean for success or failure.
👍 1
There are other implementations of
Deferred
which apply all sorts of local optimizations, but all of the ones I know about can be consumed from multiple coroutine calls to
await()
.
👍 1
v
overhead (race conditions/thread safety)
Overhead or correctness? 🙂 From the correctness perspective, everything is fine, multiple awaiters don’t affect deferred in any way. From the overhead perspective, there is some in case when
await
call suspends, but it’s negligible
b
overhead … same Deferred<T>
@Vsevolod Tolstopyatov [JB] Is that overhead any different than awaiting on two different
Deferred<T>
instead of the same one?
v
@bdawg.io overhead in terms of what? Taking into account allocation of the second deferred? In such matters there is no “X better than Y” answer. Usually, you have to measure for your particular use case
b
In terms of
there is some in case when
await
call suspends
Is there any difference in overhead of calling the suspending
await()
twice on the same
Deferred<T>
vs on two different
Deferred<T>
. Particularly to answer the
overhead
part of the question of the OP
v
then there is no difference 🙂