Alexey Romanov
Alexey Romanov

Reputation: 170815

Can `SendChannel.offer`, `CompletableDeferred.complete`, and similar be called outside coroutines?

CompletableDeferred documentation says

All functions on this interface and on all interfaces derived from it are thread-safe and can be safely invoked from concurrent coroutines without external synchronization.

Is it safe to call these functions outside any coroutine?

For SendChannel<E>, offer and close are not suspend and so they can be called outside coroutines syntactically, but is it actually safe to do so?

If a coroutine is needed, what is the cheapest way to start one: launch(Unconfined)?

Upvotes: 1

Views: 292

Answers (1)

Roman  Elizarov
Roman Elizarov

Reputation: 28678

It is safe to call offer and close from anywhere. That is what documentation means to say with "are thread-safe" phrase.

One of the reasons these methods are included into channel APIs is to enable integration of coroutines with the regular non-coroutine world that is based on various callbacks and event handlers. You can see the actual example of such integration in this guide on UI programming with coroutines.

Upvotes: 1

Related Questions