IdleStateHandler - adding and removing the same instance on same pipeline

Viewed 134

I need to be able to add and remove the IdleStateHandler on the pipeline based on certain conditions. I create one instance of IdleStateHandler per channel and save the reference to that instance in a connection class.

However when I remove the handler and then add it back, I get an exception that the handler cannot be added multiple times because it is not Sharable.

I understand not being able to share the same handler across multiple channels. However, in my case, the handler instance is unique to each channel. Why would this require the handler to be sharable? Are there any workarounds for this? I know I can create a new instance each time, but we are trying to reduce the number of new objects we create.

2 Answers

Most handlers have some sort of life-cycle which makes it challenging to support remove and re-add again. That said I guess it could be done... As of today there is no way to make it work with IdleStateHandler so you need to create the handler again. That said I wonder why you not just can have another handler in the pipeline which will either forward the IdleStateEvent or just suppress it. This would be kind of the same as removing the handler if you not want to have these events.

As Norman stated, current design is not supposed for IdleStateHandler to be reusable. You have to create new IdleStateHandler and replace the old one with new instance.

Right now when handler added to the pipeline - pipeline marks the special state field boolean added within ChannelHandlerAdapter as true. However, when handler is removed this flag is never reverted back. So when you try to add this handler again you get the exception (as added is still true).

Actually, you can change this flag via reflection to false after handler is removed from the pipeline and reuse it. But I do not recommend you to follow this direction.

Related