Visus Zhao
Visus Zhao

Reputation: 1154

In netty, how can I catch all channelClosed event?

We have a HTTP service with massive small requests, and most of them are requested only once (about 70%)

So if we keep a channel open when a request comes, soon there will be a LOT of channels staying in memory while doing nothing.

Currently what we do is to register an IdleStateHandler and an IdleStateAwareChannelHandler, so that any channel with no activity for 5 seconds will be closed.

this seems to work, and the size of opened channels are stable.

But we have another issue:

For each opened channel, we have custom made ServerConnection object associated with it, to store some useful information related to the current channel. We keep those ServerConnection in a global map called connectionMap, with the key being the channel.

Each time messageReceived is called, we check whether the channel is already in the connectionMap, if not, a new ServerConnection is created.

Each time a channelClosed/exceptionCaught event is detected, we call connectionMap.remove to remove it.

And we manually remove from the map when IdleStateHandler is invoked.

But some of the ServerConnections are not removed, while its Channel's state is actually closed.

Did we miss something? Is there any other place that a Channel is closed, but we forget to catch the event?

Upvotes: 2

Views: 1195

Answers (1)

Brian Roach
Brian Roach

Reputation: 76898

You can get notified when a channel closes by using the ChannelFutureListener interface and registering with the channel's close future.

class MyClass implements ChannelFutureListener
{
    // Whatever stuff this class also does 
    // ...

    public void operationComplete(ChannelFuture future) throws Exception
    {
        System.out.println("This channel closed! " + 
                           future.getChannel().getId().toString());
    }

}

Then for your channels you do ...

channel.getCloseFuture().addListener(instanceOfMyClass); 

When a channel closes, your ChannelFutureListener gets notified.

Note this is Netty 3.x. Netty 4.x changed the method names on a few things which you'll need t adjust for (they dropped the get prefix from the getters).

Upvotes: 4

Related Questions