Thursday 19 November 2009

Java Memory Debug Command Line Settings

Analysing memory usage and checking for memory leaks is an integral part of any Java application developmkent. This is especially true for swing apps, where swing design lends itself to creating leaks (lots of listeners with different lifespans, some of them static, SWING TIMER!).

Here's my typical command line arguments when I'm running in debug mode, enjoy.

set MEMORY_DEBUG_ARGS=-agentlib:hprof=file=myheapdump.hprof,format=b -verbose:gc -XX:+HeapDumpOnOutOfMemoryError -XX:+HeapDumpOnCtrlBreak

set LOW_MEMORY_HEAP=-ms128m -mx128m

Tuesday 3 November 2009

Builder Pattern

I've gotten round to improving some of the more complicated domain objects today by making them a) immutable b) use builders and c) use default serialisation techniques which has been an overall success.

Making the objects has become quite necessary since objects are serialised throughout our distributed system and the instance you're holding might be stale and any of the fields changed on this may overwrite the latest data, so really you want to request a change and some time later receive the updated object and typically display it until all that happens again.

The best way of doing this that I've found is the builder pattern from the Effective Java (2nd edition) book, while also trumping some of the other builder patterns I've seen. Basically the domain object has an inner Builder class with mutable data, and a build method which returns the domain object with it's data passed to the objects constructor. I'm not going to give a code sample since no one is reading and you should check out the book, go to Waterstones :P

Other problems have been finding the true identity of an object for equals and hashCode, is it really a combination of all of the fields or is it a select few containing the true ID of the object? Its far better to keep this data in it's own class or else the clutter will consume the intent of your code.

Serialisation was hit and miss, the end result was turning a class that serialised into 35 bytes into one that took 208. More investigation is needed because there is far more to it than I originally thought. I'm not really impressed by all of the magic methods like readObject, readResolve etc. Shouldn't this have been wrapped up in an interface, if only to provide some code completion?