2

I have a map as below and once I get the immutable version of the original map, I don't need the original one anymore. Is there a way to have the GC recycle it?

Map<String, String> map = new TreeMap<>();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");

ImmutableMap<String, String> IMMUTABLE_MAP = ImmutableMap.copyOf(map);
injoy
  • 3,993
  • 10
  • 40
  • 69

2 Answers2

6

The other answer is right, but what you should try to do is to use

ImmutableMap<String, String> map =
         ImmutableMap.<String, String>builder()
    .put("1", "one")
    .put("2", "two")
    .put("3", "three")
    .build();

The builder is optimized for what it does and you can often write it all in a single expression.


Even much better is

ImmutableMap<String, String> map = ImmutableMap.of(
    "1", "one",
    "2", "two",
    "3", "three");

which works for up to four key-value pairs.

maaartinus
  • 44,714
  • 32
  • 161
  • 320
5

You can make the Map eligible for garbage collection by not having any references to it anymore. This will automatically happen when map goes out of scope. If that is "too late" for you, you could explicitly assign null to map.

Either way, the actual garbage collection happens in the background when the JVM feels like it.

Thilo
  • 257,207
  • 101
  • 511
  • 656