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
Thursday, 19 November 2009
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?
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?
Wednesday, 21 October 2009
Guice in a Java Swing App
Recently I have been working on a project that as normal uses Swing but decided to use Guice to avoid some of the problems that I’ve encountered in previous projects.
The problem is that if you have components that rely on service type interfaces that are nested several layers deep (not that unlikely in a complex UI) then to pass the service to the component all the other components above it need to have methods/constructors that pass the service down the hierarchy. This culminates in a simple change to a component that needs a reference to a new service requiring changes to 4/5 classes that also now have references to something they didn’t need to know about. This means extra coupling and more pain when you’re trying to refactor.
So now there are panels which have references to components that are themselves injected, which have injected services and everything works. It just works. In fact I barely think about it anymore, components with dependencies are just injected and there are no problems, no extra dependencies and no extra work. If the injected components also need service dependant components then they are injected as well and have no impact up the hierarchy.
Many classes in the project now have no code depending on the way they are created, which is a real joy. I haven’t heard this benefit touted by IoC propaganda but it really should be. If you ever wondered if adding dependency injection was overkill for you project, note down what you would inject. If there is more than two (my own measurement) injectable classes then the gains will be more than the cost of complexity in setting up the IoC infrastructure with modules and injectors etc.
The problem is that if you have components that rely on service type interfaces that are nested several layers deep (not that unlikely in a complex UI) then to pass the service to the component all the other components above it need to have methods/constructors that pass the service down the hierarchy. This culminates in a simple change to a component that needs a reference to a new service requiring changes to 4/5 classes that also now have references to something they didn’t need to know about. This means extra coupling and more pain when you’re trying to refactor.
So now there are panels which have references to components that are themselves injected, which have injected services and everything works. It just works. In fact I barely think about it anymore, components with dependencies are just injected and there are no problems, no extra dependencies and no extra work. If the injected components also need service dependant components then they are injected as well and have no impact up the hierarchy.
Many classes in the project now have no code depending on the way they are created, which is a real joy. I haven’t heard this benefit touted by IoC propaganda but it really should be. If you ever wondered if adding dependency injection was overkill for you project, note down what you would inject. If there is more than two (my own measurement) injectable classes then the gains will be more than the cost of complexity in setting up the IoC infrastructure with modules and injectors etc.
Friday, 22 May 2009
DMA
I've had a frustrating day wrestling with my sound recording setup. The Mircotrack 2 that I'm using seems to have toasted one of my compact flash cards, now it crashes Windows Explorer!
The problem was fixed by turning off DMA on the Microtrack recorder and now it's recording properly again. DMA is a mechanism for circumventing the CPU, while writing to memory on a different device.
Thanks to Mr Sandiford for figuring this out :)
Wednesday, 4 March 2009
Referencing Enclosing Instance of an Inner Class
When using an inner class how do you reference the enclosing class? The answer is
Object.this where Object is the class type of the enclosing class. Sweet :)
Sunday, 11 January 2009
Setting a custom cursor which doesn't get resized
When setting a custom cursor in Swing you shouldn't really rely on the
To me this seems pretty crap because the image is going to get resized at some point depending on the platform your app is being run on which will most likely make the cursor image look terrible, perhaps to the user, unusable. IMO the behaviour should be to create a new image of the dimensions of
Implementation is below...
createCustomCursor method to use your images in any respectful way. The behaviour of this method is to resize the image into the dimensions returned by the getBestCursorSize method, which on Windows XP always seems to return 32x32 pixels.To me this seems pretty crap because the image is going to get resized at some point depending on the platform your app is being run on which will most likely make the cursor image look terrible, perhaps to the user, unusable. IMO the behaviour should be to create a new image of the dimensions of
getBestCursorSize and draw the supplied image at point 0,0. This does cause a problem if your image is larger than the dimension but your would be screwed the default way anyway.Implementation is below...
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
public class SizedCursor
{
public static Image getPreferredSizedCursor(
Image image)
{
Dimension bestDimension = Toolkit
.getDefaultToolkit()
.getBestCursorSize(
image
.getWidth(null),
image
.getHeight(null));
if (bestDimensionsEqualsImageSize(
image,
bestDimension))
{
return image;
}
else
{
BufferedImage resizedImage = new BufferedImage(
bestDimension.width,
bestDimension.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) resizedImage
.getGraphics();
g.drawImage(
image, 0,
0, null);
return resizedImage;
}
}
private static boolean bestDimensionsEqualsImageSize(
Image image,
Dimension bestDimension)
{
return bestDimension
.getWidth() == image
.getWidth(null)
&& bestDimension
.getHeight() == image
.getHeight(null);
}
}
Tuesday, 16 December 2008
Java Garbage Collection for String literals
Tonight I had a ponder about Javas garbage collection mechanism and what would make an object held by a WeakReference be garbage collected. The answer was quite simple, create a instance of a variable, create a WeakReference for it, null the instance and call System.gc(). I'm guessing that the instance would be garbage collected on the next natural sweep but because I was using a unit test I needed it to be done straight away.
However, garbage collection on string literals is far more interesting. See the unit tests.
All of these tests pass. Notice the last test, even after the string instance has been nulled the WeakReference still has a not null value. After a bit of googling I found that string literals are referenced from Javas 'String Literal Pool' which is a cache for string literals so is not eligible for garbage collection!
However, garbage collection on string literals is far more interesting. See the unit tests.
import static org.junit.Assert.*;
import java.lang.ref.WeakReference;
import org.junit.Test;
public class ReferenceTest
{
@Test
public void testWeakReference()
{
Object reference = new Object();
WeakReference<Object> weakRef =
new WeakReference<Object>(reference);
assertNotNull(reference);
reference = null;
// reference will not be null
// without garbage collection here
System.gc();
assertNull(weakRef.get());
}
@Test
public void testWeakStringReference()
{
String reference = new String();
WeakReference<String> weakRef =
new WeakReference<String>(reference);
assertNotNull(reference);
reference = null;
// reference will not be null
// without garbage collection here
System.gc();
assertNull(weakRef.get());
}
@Test
public void testWeakStringLiteralReference()
{
String reference = "my reference";
WeakReference<String> weakRef =
new WeakReference<String>(reference);
assertNotNull(reference);
reference = null;
// does not matter if garbage collection
// is here or not but lets do it anyway
System.gc();
// !!!
assertNotNull(weakRef.get());
}
}
All of these tests pass. Notice the last test, even after the string instance has been nulled the WeakReference still has a not null value. After a bit of googling I found that string literals are referenced from Javas 'String Literal Pool' which is a cache for string literals so is not eligible for garbage collection!
Subscribe to:
Posts (Atom)