This week's book giveaway is in the Other Open Source APIs forum. We're giving away four copies of Storm Applied and have Sean Allen, Peter Pathirana & Matthew Jankowski on-line! See this thread for details.
"Disposes of this graphics context and releases any system resources that it is using. A Graphics object cannot be used after disposehas been called.
When a Java program runs, a large number of Graphics objects can be created within a short time frame. Although the finalization process of the garbage collector also disposes of the same system resources, it is preferable to manually free the associated resources by calling this method rather than to rely on a finalization process which may not run to completion for a long period of time.
Graphics objects which are provided as arguments to the paint and update methods of components are automatically released by the system when those methods return. For efficiency, programmers should call dispose when finished using a Graphics object only if it was created directly from a component or another Graphics object."
I have figured out that paintComponent and the Garbage Collector work in the background, however, I would appreciate some insight on how they co-operate from a JVM architectural point of view (i.e. the mechanics), as this would help me understand more about performance.
The examples I have seen so far, do not use graphics.dispose(), how does using it or not using it affect the performance of the Garbage Collector?
Do you have more examples?
I have tried to carry out a test using NetBeans 7.0, however, the profiler I am using is too slow, perhaps you can indicate other ways of testing for performance.
I'm not exactly sure when Graphics objects are created by the toolkit, but I think each container passes a modified clone to their children, after which they dispose the clone, and finally their original as well. You will have to go through the source to see how it really works.
If you create new Graphics objects (through cloning or otherwise) you are responsible for disposing it, because the containment hierarchy doesn't know about the existence of that object. If you don't dispose of it, the resources it holds will only be collected once the garbage collector determines the Graphics object is eligible for finalization. This may cause overal performance to reduce, because there are unused resources being stored in memory.