user1365914 user1365914 - 4 months ago 11
Java Question

How many objects are eligible for garbage collector in this example

public class Currency {
String name = new String();
static Integer value = new Integer();
static void getCurrency(Integer v) {
Currency c = new Currency();
c.value = v;
}
public static void m() {
Currency.getCurrency(50);
Currency.getCurrency(100);
}
public static void main(String[] argv) {
Currency.m();
}
}


I count 5 elements eligible for garbage collector when
m()
exits. The exercise says 6 is the correct answer. Can you help me?

Answer

The two calls made to getCurrency() each will create two Currency objects in total. Each call requires:

  • an Integer object as parameter, later assigned to value
  • a Currency object
  • a name string object (not static, i.e. each Currency object has one)

3 × 2 = 6

Update:

The big question seems to be as to whether a new Integer object will be created for each call to the Currency constructor. Autoboxing a primitive int into an Integer will call Integer.valueOf(). And the Javadoc has this to say about Integer.valueOf():

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

So values in the range -128 to 127 get cached. But the catch is that in your code, you are working with two different values, 50 and 100, so caching won't avoid creation of a new Integer object AFAIK.

Comments