java stack and object returned by a method

2019-08-05 11:06发布

问题:

for statement

rs.getString("name")  //rs is java.sql.ResultSet interface

bytecode is:

41:  aload   4
43:  ldc     #10; //String name
45:  invokeinterface #11,  2; //InterfaceMethod java/sql/ResultSet.getString:(Ljava/lang/String;)Ljava/lang/String;
50:  pop

At line 45 returned string object by rs.getString("name") is pushed onto stack and at line 50, return object (a string object) is poped up.

1)Does stack contain only reference to this returned string object with actual object on heap OR stack contains the actual String object??

2) and after poping up the returned string object, will it be garbage collected OR it's memory deallocated as stack for this method vanishes???

回答1:

At line 45 returned string object by rs.getString("name") is pushed onto stack

There is no returned string object. There's a returned string reference.

Conceptually at least, objects are never on the stack, never returned, never passed. It's only ever a reference.

and after poping up the returned string object, will it be garbage collected OR it's memory deallocated as stack for this method vanishes?

The reference will be cleared when the stack pops, which means that the string object itself would be eligible for garbage collection if there are no other strong references to it.



回答2:

1) The stack only contains a reference to the object. All objects are stored on the heap.

2) The storage for the string might be garbage collected when there is no active reference to it. This is independent from whether it's popped off the stack. This is about references to that string in the entire program.



回答3:

  1. The stack has a reference to the string, not the string itself.

  2. Since you're not assigning the String, the value will be GCed when the reference to the row in the ResultSet is GCed.