Netty releaseExternalResources() hangs

Published on — Filed under protip

A not-so-uncommon issue with Netty (version 3.2 at the time of writing) is having your code hang when calling the method releaseExternalResources() either on the Bootstrap or ChannelFactory. There are a couple of reasons for this to happen:

You'll often use a ChannelGroup to keep track of all open channels and eventually call close() on that ChannelGroup to ensure all open channels are closed.

But sometimes, some rare odd times, you'll have a channel added to the ChannelGroup just after close() was called. You won't know. Until you call releaseExternalResources() and the damn thing hangs.

If you're using the ChannelGroup only as a bag of open channels so that you can cleanup correctly, this might be useful to you.

It's an extension of DefaultChannelGroup that only allows close() to be called once. Adding channels to this CleanupChannelGroup after close() has been called will result in the channel being immediately closed. Calling close() twice, will throw an exception.

You just have to make sure that your code always adds opened channels to this special ChannelGroup and you'll never have the code hang again when calling releaseExternalResources(), as long as you call close() on the ChannelGroup before.