1

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!

Finlay Weber
  • 2,989
  • 3
  • 17
  • 37
  • Is your intergration testing system using classloaders to load the application code multiple times? This can cause the newInstance method to be called multiple times with the same, key, which gives an error. – Ferrybig Feb 08 '21 at 13:41
  • None that I can see directly. Although the test is written in groovy, using the spock framework. Maybe that is using classloaders indirectly. I am not sure – Finlay Weber Feb 08 '21 at 13:46
  • Thanks for the tip, I switched `AttributeKey.newInstance` to `AttributeKey.valueOf` and now it works. Mind shedding more light why `newInstance` could lead to an error, within the answer, then I can accept it as the answer – Finlay Weber Feb 08 '21 at 13:48

1 Answers1

0

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.

Ferrybig
  • 18,194
  • 6
  • 57
  • 79
  • Won't turning off conflict detection lead to other issue down the line? – Finlay Weber Feb 08 '21 at 13:54
  • First try to see if marking the variable as "private *static* final" works with `newInstance`, turning off the conflict detection makes it a bit more unpredictable, but as long as you properly document all the used keys, and check for new keys during code reviews, it shouldn't be a problem – Ferrybig Feb 08 '21 at 13:57
  • It was "private final" before, changing it to "private static final" worked alright with `newInstance`. Thanks! – Finlay Weber Feb 08 '21 at 14:44