Overwriting a BufferedImage -> memory leak

i’ve written a threaded class which draws a background image and some rectangles on a temp buffered image,
and then draws the temp buffered image to a volatile image. performance seems to be fine, buffering working good.

but when i try to set a new background image, the old one is never disposed so my memory usage increases.
//code to overwrite the old bgImage with a new image (newMap) with different size
bgImage = gc.createCompatibleImage(newMap.getWidth(), newMap.getHeight());
Graphics2D g2d = (Graphics2D)bgImage.getGraphics();
g2d.drawImage(newMap, 0, 0, null);
g2d.dispose();

i tried to stop the thread, then replace the bgImage, and start the thread again (thought the image might be in use or something) but no use…

The code looks ok, you shouldn’t have any memory leaks, but you create a lot of
images that you actually don’t need?! Why does your map size change? Is the code
used during game play or you are just converting a map?

What’s the code good for? I think there is an easier way to do things. Creating and
disposing all these images creates a lot of overhead for garbage collection. It’s not
a memory leak, it’s just a lot of work for the GC.

after i used netbeans profiler i noticed i started a second thread which did the same operation on the same object…
this explains the memory leak. thanks for your time though :slight_smile: