i have a question about coroutine channels and garbage collection.
In a function, lets say function channelCreation(), I create a channel like this:
fun channelCreation():Channel<Int>{
val channel = Channel<Int>(1)
GlobalScope.launch{
channel.send(5)
}
return channel
}
Be aware, it has a capacity of 1.
Later, I’m going to send something through this channel, only one time.
Sometimes I use the return value of channelCreation function, and receive what has been sent. And in other times, I call channelCreation, but ignore return value.
What happens now with the channel? It is never closed and it is never received, can this lead to a memory leak, or will the channel memory be released, when no reference is there anymore?
I doubt Channel has to be closed to prevent leaks. We don’t have to “close” lists or arrays. and Channel is pretty much just a collection with support for suspending.
I would be more concerned that if you return the channel, someone writes to it and never reads, then maybe this GlobalScope coroutine will be waiting forever and keeping Channel in the memory.
Anyway, what’s the point of using channels if we don’t really write to them?
This is not the usecase, the usecase is much more complex, I just reduced it to clarify my issue. In my productive Code, channel is not returned, but a class that contains channel as private member, so it is not possible to send to the channel, except from the channelCreation function.
If you say, you doubt that channel has to be closed, means, I should better check it? Because you don’t know for sure? I also didn’t find something in the docs. Which is even worse, because now my tests could show, that there is no memory leak, and in later versions of kotlin it could lead to a memory leak, because they changed the implementation.
My point is: as a rule of thumb we don’t document that a class in stdlib/external library doesn’t require special handling to avoid memory leaks. It is the opposite: we expect classes generally don’t cause leaks and only in exceptional cases, usually related to I/O, we clearly specify all risks in the documentation.
Why would it be different in the case of Channel? What makes you think you should be more careful with Channel than ArrayBlockingQueue or HashMap? None of them specify explicitly they don’t cause leaks.
But sure, if you need guarantees or a proof, then I don’t have one.
I don’t think it would leak, assuming that you never send to the channel you return. If you change the return type to ReceiveChannel<Int>, then you should be fine.