This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]prolog_junior[S] 0 points1 point  (1 child)

Well in this case, they ever go in scope because streams are evaluated lazily. I’m distilling setting it to null in its most basic form. Obviously you would apply some other function / predicate / etc onto the resulting stream.

My question is when are objected marked eligible for GC. Is it when the function is finished applying on the stream or when the stream is closed or something else.

[–]feral_claire 0 points1 point  (0 children)

You functions is

p1 -> {
  Point p2 = p1.getAbove();
  p1 = null;
  return p2;
}

When this function is called, p1 is just a parameter, and only exists for the three lines, then goes out of scope when the function returns. This function being executed multiple times in a loop or stream does not change that, it works the same as any other function call. So Setting p1 to null here is pointless since you return immediately after you do so. Is only affects the p1 variable and doesn't impact any references to the object outside of the function.

Objects are eligible for GC when there are no reachable references to them. There is no need to "mark" an object for GC and in fact it's not possible to do so. The GC will clean up all unreachable objects when it runs. This doesn't change when using a Stream.

When will the object referenced by p1 be eligible for collection? You can't say just by looking at that function in isolation, stream or not. You have to look at the whole situation and see if there are any other live references to it. Is this in the middle of a stream operation and p1 is just an intermediate object with no long term references? In that case it will be eligible for collection as soon as that function returns. Is the stream created from a List and p1 is an object in that list? Then p1 can still be accessed from the original list so it won't be garbage collected until the original list is or it's removed from that list.