Is Kotlin's `Channel` intended to fully replace Ja...
# coroutines
m
Is Kotlin's
Channel
intended to fully replace Java's
Queue
? More specifically, for a high traffic message processing environment, should I attempt to use a
ReceiveChannel
instead of
ConcurrentLinkedQueue
? I'm thinking that the answer is yes, but if anyone can provide some reference to the intent here I'd appreciate it!
c
My understanding is that
Channel(capacity = UNLIMITED)
is intended as a replacement for
ConcurrentLinkedQueue
, yes, but I'm not an expert
m
Thanks! Yeah I'm unable to find any kind of reference to this searching online and was hoping someone knows more than I do
a
I thought that Channel was being deprecated and will be replaced with StateFlow / SharedFlow. Or maybe that was Actors? Or maybe both? https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-broadcast-channel.html There’s a lot of discussion here: https://github.com/Kotlin/kotlinx.coroutines/issues/87
c
The actor function has been deprecated, but not the pattern
m
I believe that is Actors
c
StateFlow/SharedFlow are recommended in most use cases (what people want is something to replace RxJava etc), but they're not queues
m
In this case I want to process packets concurrently as they come in. In Java traditionally a concurrent queue would be used to make the pass from the receiving thread to the processing thread(s). It seems to me that
Channel
serves a very similar purpose, but allowing for the power of suspending when there is nothing received. However, I can find very little documentation or discussion on this kind of thing for reference
c
Exactly. Flows are asynchronous but not concurrent, so you don't really have a choice here
It's not recommended to create pipelines of channels because they're a bit expensive compared to flows, but they are quite literally a suspending queue, so i think your use case fits perfectly
a
ah this is what I was remembering
Conceptually shared flow is similar to BroadcastChannel and is designed to completely replace it.
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/
m
I see! Thanks for the information. From what you guys have said I do believe
Channel
is correct for my use case, but I also appreciate the extra info on flows as I've only read up on the cold flows much. I will definitely be able to make use of those in other reactive areas of my projects
k
Channels are for communicating between coroutines. Those coroutines may or may not be executing on separate threads. Flows can often serve the same purpose, but not always. If you’ve ever used golang, the same concept applies here.
Do not communicate by sharing memory; instead, share memory by communicating.
Channels should be used for this exact reason.
309 Views