Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What closing a kotlinx.coroutines channel does

What closing a kotlinx.coroutines channel using channel.close() does and what the negative effect of not manually closing channels would be? If I don't manually close a channel will there be some unnecessary processing? Will there be a reference to the channel somewhere that prevents it from being GCd? Or does the close function just exist as a way of informing potential users of the channel that it can no longer be used.

(Question reposted from Kotlin forum https://discuss.kotlinlang.org/t/closing-coroutine-channels/2549)

like image 540
Roman Elizarov Avatar asked May 10 '17 09:05

Roman Elizarov


People also ask

What are channels in coroutines?

A channel is conceptually similar to a queue. One or more consumer coroutines can read from the same channel. A channel has a suspending send function and a suspending receive function. This means that several coroutines can use channels to pass data to each other in a non-blocking fashion.

What is run blocking in coroutines?

runBlocking starts the coroutine which calls CoroutineScheduler. dispatch(). dispatch() posts targeted runnable block of code to main thread handler. BlockingCoroutine blocks current thread with LockSupport.

How do I cancel coroutines?

Coroutine cancellation is cooperative. A coroutine code has to cooperate to be cancellable. All the suspending functions in kotlinx. coroutines are cancellable.

Why are my coroutines slow?

If all the cores of your machines are nearing 100% when your program is running, then the whole machine will become slow, not only your coroutines! The way out in this case is to either optimize your program to use less CPU, distribute the work more evenly across the available cores, or simply upgrade your machine.


1 Answers

Closing a channel conceptually works by sending a special "close token" over this channel. You close a channel when you have a finite sequence of elements to be processed by consumers and you must signal to the consumers that this sequence is over. You don't have to close a channel otherwise.

Channels are not tied to any native resource and they don't have to be closed to release their memory. Simply dropping all the references to a channel is fine. GC will come to do clean it up.

like image 170
Roman Elizarov Avatar answered Oct 03 '22 11:10

Roman Elizarov