0

I am running a game, when I start up I load images into a WeakHashMap of Images. When I run my game, my RAM just keeps going up, then eventually my WeakHashMap just unload all of their data. Is this relates to Garbage Collection? Any solutions?

Trying
  • 14,004
  • 9
  • 70
  • 110
Solplex
  • 9
  • 2
  • 5
    What did you expect? You only use a `WeakHashMap` when you want entries to get removed whenever the key can be garbage collected. – Louis Wasserman Apr 30 '13 at 00:00
  • WeakHashMap is intended to be used for a cache, where data may go "poof" from time to time, but can be reloaded from the network or some other source if that occurs. – Hot Licks Apr 30 '13 at 01:28

3 Answers3

1

You can create a HashMap using SoftReferences instead of WeakReferences - the garbage collector will be a bit less eager about GCing it. Just copy the WeakHashMap source code, replacing the WeakReferences with SoftReferences.

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
0

As Louis Wasserman suggested this is expected behaviour. I think you may want a normal hashmap. Please read the docs regarding WeakHashMap at http://docs.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html

Adrian
  • 495
  • 2
  • 10
0

A java.util.WeakHashMap is a type of map that, as its description might suggest, keeps only weak references to its keys. Weak references, as you know, are references that do not prevent the garbage collector from collecting the referenced objects. In order to prevent an object from being garbage collected, you must maintain a strong reference to the object somewhere.

If you want the data to be protected from garbage collection, store it in a regular HashMap. For your particular application, you may want to write your own map implementation that keeps soft references (references that the gc only clears if it has to, rather than always clearing) to the images, and have it automatically load missing art when that art is called for. (Could be tricky if you need it to be all thread safe, though...)

AJMansfield
  • 4,039
  • 3
  • 29
  • 50