Search code examples
nettynetty4

How to fix AttributeKey leading to IllegalArgumentException in Netty 4


I am porting a Netty 3 application to Netty 4. The Netty 3 application uses Attachement to attach objects to the context.

Reading New and noteworthy in 4.0 I see Attachment has been removed and replaced with AttributeKey/AttributeMap.

The problem is this works when I run the application, but under integration testing, I get the error:

Caused by: java.lang.IllegalArgumentException: 'attr_key' is already in use

Where attr_key is defined in a shareable Handler has follows:

private final AttributeKey<Object> ATTR_KEY = AttributeKey.newInstance("attr_key");

and then used somewhere else in the same handler class as follows:

channel.attr(ATTR_KEY).set(new Object())

Any ideas or thoughts on the recommended way to use AttributeKey/AttributeMap to prevent this error? Thanks!


Solution

  • When using Attribute keys, make sure you only construct them 1 time.

    This means, you need to store them inside a private static final variable, a private final variable is not good enough, as it gives error when the class is constructed multiple times.

    If it is impossible to make sure the method newInstance method is called a single time, you need to use AttributeKey.valueOf, so it turns off conflict detection. This is required for some unit testing framework, where the libraries are loaded 1 time, but the application code is dynamically restarted.