0

Another conceptual question.. I am fighting against a java heap space exception. My problem is, that i have to render/display small but a lot of images. I exceed maximal ram. (edit vm options does not help) Yet i store all images in one List. I think about if it may need less ram if i render the images one by one and store it temporary on local hard disk. Will the images be still all in ram if displayed on screen?

Changes in the code would be significant so i want to ask this before..

Java D
  • 424
  • 1
  • 7
  • 18
Jan S
  • 117
  • 3
  • 13
  • 1
    Only load those images that are actively on the screen, keep a list to the source of the images and load those you need when you need them. Make sure you completely deterrence those images you don't so that the GC can free up memory – MadProgrammer Jun 21 '13 at 23:49
  • ok so i wil change the program to store the images on disk.. thx. . Does a Scrollpane do this job? (only load what is displayed)? jscrollpane api does not answer this directly.. but the wording "scrollable client" make me expecting that it does so.. – Jan S Jun 22 '13 at 00:16
  • Yes and no. Once the images are loaded they main remain in memory. There's no easy way to know when you component goes out of view – MadProgrammer Jun 22 '13 at 00:20
  • I found sth that looks useful here.: http://stackoverflow.com/questions/13627783/how-to-check-whether-jcomponent-inside-jscrollpane-is-visible-to-a-user i will check it tomorrow. thank you – Jan S Jun 22 '13 at 00:51

1 Answers1

1

If your use case is lots of images/icons in a JList/JTable inside a JScrollPane, I once wrote something similar for a CMS search result display:

I had thumbnails of larger images stored on server/cached on disk. You can exploit the fact that the JList/JTable (or Swing components in general) will only try to paint the components visible on screen, so you don't need to track this yourself. I used a JLabel with ImageIcon as renderer in the list, and a fixed size cache of icons in memory. Whenever the renderer hit an image not in cache, I used a lazy-loading technique with a placeholder icon returned immediately, while loading the icon in the background using a SwingWorker. When loaded, the SwingWorker issued a repaint to JList. The icon would now be in cache, and the list would paint nicely.

Some bonus tips: Make sure your icon cache is larger than the maximum number of items that can be displayed on screen. Also, use a limited (fixed size) thread pool for your SwingWorkers (possibly loading multiple icons at once), to avoid exessive reapint-loops that may cause flickering.

Harald K
  • 23,992
  • 6
  • 49
  • 97