rhollencamp
rhollencamp

Reputation: 533

Short-lived vs Long-lived for static data

I understand how the generational garbage collection HotSpot JVM uses works. We have a method that returns a list of static data, along the lines of

public List<String> getList() {
    List<String> ret = new ArrayList<String>();
    ret.add("foo");
    ret.add("bar");
    return ret;
}

I was considering rewriting this as

private static List<String> list = null;
...
public List<String> getList() {
    if (list == null) { .. initialize here .. }
    return list;
}

this would only create the list once. This single list instance would eventually make its way into the tenured generation. Since this is a rather large app, using this design pattern in many places would mean there are a lot of these static lists in the tenured generation - increasing memory usage of the app.

If we follow the pattern of creating and returning a new list every time, said list would never make it out of eden before being garbage collected. There would be a bit more work involved - having to create and fill the list, and work in garbage collecting - but we would use less memory overall since the list doesn't last long.

This question is more academic in nature, as either pattern will work. Storing a static list will increase memory usage by an insignificant amount, and creating the list every time will increase workload by an insignificant amount. Which pattern to use probably depends on a number of factors - how often the list is used, how much memory pressure the app is under, etc. Which pattern would you guys target, andy why?

Upvotes: 1

Views: 256

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533560

Storing a static list will increase memory usage by an insignificant amount

It will use more space when there is no real need for it. It will be the same if there is one usage of it. But if you have more than one copy, the static version is more efficient.

Often it's not the best case which will kill you, it's the worst case. In the worst case there will be large numbers ?millions? of copies of the collection.

Upvotes: 4

artbristol
artbristol

Reputation: 32417

As Peter Lawrey points out, in the non-static case, sometimes you will be using a lot more memory than necessary while the GC is waiting to do its thing.

I would concentrate on what's more readable. To me, Guava's ImmutableList.of in a static final field says immediately this data isn't going to change.

(Or Collections.unmodifiableList(Arrays.asList(...)) if you don't want Guava)

Upvotes: 0

Related Questions