Pragmatic Programmer Issues

WeakReference common mistake

Last weekend I was on NetBeans Platform Training conducted by Geertjan and Karol Harezlak from Sun Microsystem. This was a great training. One slot was about Netbeans Issuezilla and how to contribute, provide patches and so on. Karol showed us his daily work, and he showed one of the bugs he had reported and how looks all the process from issue report to make issue resolved.

All attendees try to help Karol to do this, I’ve got some fillings that the solution is still wrong but I wasn’t sure. So after training I’m came home and try this.

Code Snapshot:

codesnapshot

Wrong method : The problem is that after checking that  we have a reference and it is not null, and using it we may have gc executed and another call to refString.get() is null !!!

wrong-method

Good method: We crate strong reference during all method execution so both refString.get() is null or not during all method body.

good-method

To run this you should adjust -Xmx parameter. -Xmx256m works for me.

So the problem is that even we check reference is not null, garbage collector can start and after check we’ve got  NullPointerException. The solution is easy, we must make strong reference (just for the method execution).

I hope this will help you in daily life.  Here is source file, so you can check it on yout own.

Categories