Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does return value go in java if no variable assigned to accept it?

Tags:

java

Let's say a method returns some value, but when I call it, I don't assign any variable to accept this RV. Then where does it go? Will GC collect it? Would it be a problem if I use this kind of method tons of times in my code?

like image 955
M老立 Avatar asked Sep 07 '25 17:09

M老立


1 Answers

Then where does it go?

It doesn't go anywhere. The value / reference is simply discarded. It is as if you assigned it to a local variable that immediately goes out of scope.

Will GC collect it?

It will be garbage collected when the garbage collector detects that it is unreachable. In your example, the method doesn't put the object reference anywhere else, so it will be unreachable immediately.

Note that even if the object is immediately unreachable, it may take some time for the GC to notice this and collect it. (But that's not a bad thing. It is considerably more efficient to forget the object reference and deal with later than to try to reclaim the space immediately.)

Would it be a problem if I use this kind of method tons of times in my code?

Not necessarily. The example code is not doing anything useful, and hence the overheads of allocating the object and then garbage collected are simply a waste of resources. But if it was doing something useful, the overheads are not likely to be a problem. (In ideal conditions, allocating and garbage collecting an object is cheap in Java.)

Unnecessary allocation can be a problem in some cases though:

  • If you are running with a heap that is too small for the application's working set of objects, the overheads can ramp up.

  • HotSpot's default "throughput" GC will "stop the world" while the GC is running, so excessive allocations will increase the number o f GC pauses that you experience. (This may or may not matter ... depending on the application.) You can mitigate this by using CMS or G1 as your collector, but that introduces overheads in other areas.

like image 162
Stephen C Avatar answered Sep 10 '25 05:09

Stephen C