Previous Page
Next Page

7.7. Image Caching

Image is a Java construct that wraps a native resource and thus must be properly managed. As with all other native wrappers in Eclipse, the rule is that if you create it, you must dispose of it to prevent memory leaks. ImageDescriptor, on the other hand, is a pure Java type that identifies a particular image without its associated native resource. It does not need to be managed and removed properly; rather, it will be automatically managed and disposed of by the Java garbage collector.

When a plug-in creates an instance of Image, it typically caches it in an object that maps the identifier for the imagetypically an ImageDescriptorto a particular image. Not only does the cache provide a way to remember which Image instances were created and thus need to be cleaned up, but it also keeps the same image from being loaded into memory more than once, preventing unnecessary usage of limited OS resources. Depending on where and when the image is used, the image cache may be disposed when the view closes, or it may be kept around for the life of the plug-in.

In the Favorites plug-in, if you need to load your own images (see Section 7.2.3, View model, on page 265), instantiate a class similar to the one below to cache loaded images. This class follows the Eclipse approach by lazily loading the images as they are requested rather than loading all images immediately when the plug-in starts or when the view is first opened. The plug-in's stop() method would be modified to call the dispose() method of this instance so that the images would be cleaned up when the plug-in is shut down.

package com.qualityeclipse.favorites.util;

import ...

public class ImageCache {
   private final Map imageMap = new HashMap();

   public Image getImage(ImageDescriptor imageDescriptor) {
      if (imageDescriptor == null)
         return null;
      Image image = (Image) imageMap.get(imageDescriptor);
      if (image == null) {
         image = imageDescriptor.createImage();
         imageMap.put(imageDescriptor, image);
     }
     return image;
   }

   public void dispose() {
      Iterator iter = imageMap.values().iterator();
      while (iter.hasNext())
          ((Image) iter.next()).dispose();
      imageMap.clear();
   }
}

Alternatively, you can use the class org.eclipse.jface.resource. ImageRegistry or the Plugin.getImageRegistry() method.

Tip

WindowBuilder Pro (see Appendix A, Eclipse Plug-ins and Resources) provides a ResourceManager that caches images, fonts, cursors, and so on.



Previous Page
Next Page