WeakReference common mistake

Posted in java by pedro | Wednesday, April 1st, 2009 at 4:55 am

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.

One Response to “WeakReference common mistake”

  1. [...] outcome of NetBeans training I was mention in previous post was information about java.util.ServiceLoader [...]

Leave a Reply

about me

My name is Sebastian Pietrowski. I've finished Warsaw University as Master degree. I started my journey with Java 1.1 with Thread and JDBC programing in 1998 as I worked for merlin.pl. In 1999 I've passed Java Programer Certificate for Java 1.2, and was solution architect of merlin.pl infrastructure when we was moving from pl/sql to J2EE. It was great performance optimization with 10 times more req/sec than in requirements and 85 times faster as original solution.

Currently I work as Expert Software Development Java at F.Hoffmann-La Roche. The company was founded in 1896 and today, Roche employs over 80.000 people. After work I'm involved in activities related to Scala/Lift, Ruby/Rails/Merb, Python/Django. This is because I try to be pragmatic also I'm focused on application performance and tuning with success in my daily work.

My Yoda's motto: Do, or do not. There is no try.