Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory management : how to reset a list correctly

Tags:

java

memory

In terms of memory used and impact on garbage collector, I would like to know if there is a difference between those two implementations :

protected List<T> _data = new ArrayList<T>();

// I want to reset this list using another one. First try :
public void set(List<T> newData) {
    _data = newData;
}

// I want to reset this list using another one. Second try :
public void set(List<T> newData) {
    _data.clear();
    _data.addAll(newData);
}

Also, if there is any functional difference, please tell me !

like image 748
C4stor Avatar asked Jun 21 '13 13:06

C4stor


1 Answers

The first one just replaces its reference to a list with the one provided by the caller. If the old list isn't reachable from anywhere else, it is eligible for GC.

The second uses the object's existing list, and copies each of the caller's list's item references into it. If that increases the size of the collection, then that may involve allocating a bigger array internally (making the smaller array collectible).

The reachability of the items themselves does not change; both versions cause the lists to refer to the exact same items.

The first is typically quite a bit faster, since you're replacing a single reference. That's less work than copying a bunch of references from one list into another.

The second, though, is generally better from an encapsulation point of view. Imagine this...

yourThingie.set(myItems);
myItems.add(objectYouNeverWouldHaveAllowed);

With the first version, _data now contains objectYouNeverWouldHaveAllowed. You can no longer enforce your class's constraints on _data; since you've let the caller smuggle their own list in there, they now have control over your object's internal state. They can break your object from a distance, even accidentally.

The second doesn't have such a problem. You retain control of _data, the caller's subsequent changes to their list don't affect you, and if you're not doing something broken (like providing a getter that retrieves the naked object), you're safe.

like image 97
cHao Avatar answered Sep 23 '22 10:09

cHao