File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes JVM caching images?! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "JVM caching images?!" Watch "JVM caching images?!" New topic

JVM caching images?!

John Blanco

Joined: Jan 13, 2005
Posts: 20
It seems to me that the ImageIcon class (and Toolkit) are caching images that I load. This is causing me an issue because I am writing a map editor, and when someone updates the actual image of tiles, I want to be able to "Refresh" the screen and reload the graphic.

I had an elaborate image cacher in my code, and drop the cache when I need to refresh -- and now I learn that Java is doing it behind the scenes?

How can I drop the cache so I can redisplay the image? Any technical way, or clever workaround?
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
This is a bit of a non-answer, but if you're working with tiled images perhaps you should look at RenderedImage and JAI. I haven't delved too far into it but a big part of what it offers is precise control over tiled images.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Don't blame the JVM, it's the library! The API for java.awt.Toolkit.getImage states:

The underlying toolkit attempts to resolve multiple requests with the same filename to the same returned Image. Since the mechanism required to facilitate this sharing of Image objects may continue to hold onto images that are no longer of use for an indefinite period of time, developers are encouraged to implement their own caching of images by using the createImage variant wherever available.

The documentation in javax.swing.ImageIcon doesn't reveal all, but the constructors that are passed a URL or a filename string use Toolkit's getImage in all the source code from Sun I've read.

Advice: avoid Toolkit's getImage, and the ImageIcon constructors that take a filename string or URL. I'd like to learn the JAIm but it keeps getting bumped down my to-do list (work, *sigh*), however reading images with javax.imageio.ImageIO is a snap, and there is no caching:
BufferedImage is a subclass of Image. There's no need to use MediaTracker or ImageObserver with it -- its pixels are always in memory.

There is no emoticon for what I am feeling!
John Blanco

Joined: Jan 13, 2005
Posts: 20
Wow...another library. Java stays too far ahead of me. :-) Thanks, worked great!
I agree. Here's the link:
subject: JVM caching images?!
It's not a secret anymore!