|
|
|
Back to newsletter 159 contents
This month I've got a little puzzle for you. How can you get a null pointer exception from the following piece of code?
//map is an instance of HashMap x = map.get("hello");To be clear, "map" is not null, it is an instance of the standard HashMap class from the JDK, the get() method and all the other HashMap methods are the normal ones you have in the JDK, and there has been no bytecode injection. Oh, and the process is not out of memory, hasn't been out of memory, and the HashMap instance has not been used in more than one thread.
Maybe you've figured it out already? If not, here's a hint (before I tell how you just below), it's related to a performance anti-pattern. If you like puzzles, figure it out before reading on ...
This NPE was an actual problem a colleague encountered. He was unable to debug the configuration that caused it, so he only had the stack trace and the code. Many hours of code path analysis left him with the finding that a HashMap.get() was throwing an NPE, and the HashMap instance was definitely not null, just as the code fragment above shows. I'm sure you've figured it out yourself now, but if not, let me reveal one more hint - the signature of "x" matters.
Got it? Here's enough code to recreate the bug yourself
int x; HashMap<String,Integer> map = new HashMap<String,Integer>(); x = map.get("hello");
The auto-unboxing of the non-existent value was, of course, the issue. I know autoboxing was introduced to make coding easier, but it's a definite performance anti-pattern and can lead to annoying bugs like this which are non-intuitive. Personally, I always try to remove autoboxing by making any such calls explicit, so that although the code is a little uglier, it's also clearer what's happening.
Now on to yet more links to Java performance tools, news, articles and, as ever, all the extracted tips from all of this month's referenced articles.
Java performance tuning related news.
Java performance tuning related tools.
Back to newsletter 159 contents