0

Suppose I have a Map<String,List<SomeObject>> someMap; whose size() ranges from 1 to 100 (this size() stays the same for the duration of the program, the keys also stay the same!). However, in my program, the values associated with the keys are constantly changing.

The way it's currently set up is that each time I need to change someMap's values (note that whenever I need to change the value corresponding to one key, it happens that I also need to change the values corresponding to every key), I'll overwrite the old map with a new HashMap<String,List<SomeObject>>(), then someMap.put(someString,listOfSomeObjects) 1 to 100 times.

I am wondering how to minimise the amount of garbage generated by this program? I understand that I have a few options here; I could do what I'm currently doing, or I could rely on the clear functionality (either applied at the HashMap level and re-putting the List<SomeObject> instances into it, or applied at the valueSet() level.

The context is a real time system where stop the world pauses are undesirable (but also I don't want to purchase a special JVM for this).

user2763361
  • 3,789
  • 11
  • 45
  • 81
  • Don't know too much about GC, but replacing the entire map each time sounds like a place to improve. Couldn't you keep the Map with all its strings and all its lists, then just add and remove the `SomeObject` instances from the lists? – Dan Temple Mar 18 '14 at 10:59
  • @DanTemple that's not the case, allocation in Java's generational memory scheme is v-cheap, as is the collection of un-referenced objects when using a *copying* GC algorithm – Nick Holt Mar 18 '14 at 11:07

1 Answers1

1

There's lots of variables at play here and without proper profiling it's hard to give a definitive answer, but in general, I'd carry on as you are because:

  • the maps and their contents are unlikely to make it out of the young generation, which is cheap to GC
  • copying the map means you don't need to synchronize with other threads that have reference to the original instance (unless your behavior explicitly requires it)

You should try using different GC algorithms on the young generation while profiling your app. I'd be tempted to look the ParNew, which while it's technically stop-the-world, is normally so quick that's irrelevant.

Nick Holt
  • 33,455
  • 4
  • 52
  • 58