-1

From this post Strong references never be garbage collected, With this understanding I assume if we create a infinite Strong Reference objects in memory then it must throw OutOfMemory error.

However, When I ran below dummy program it never through OutOfMemory error although I have created infinite objects in while loop.

public class Test2 {
    public static void main(String[] args) {
        while (true) {
            Test2 obj = new Test2();
            System.out.println(obj);
        }

    }
}

Please help me understand if strong referenced objects are never garbage collected then how come there is no OOM error.

T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 1
    They're garbage collected as soon as they go out of scope; that is, immediately. – shmosel Sep 29 '17 at 05:58
  • @shmosel- Did you read the post i attached ? It has 80 Likes on the answer , if you have know something else please elaborate in answer so that we can understand..please – T-Bag Sep 29 '17 at 06:02
  • 1
    Yes, what's your point? There's no such thing as a "Strong Reference object". Your code creates many objects, but only allocates a single strong reference. – shmosel Sep 29 '17 at 06:04
  • @shmosel-- Yes understand it know with the help of Louis and piet.. Thanks – T-Bag Sep 29 '17 at 06:06

2 Answers2

1

You don't keep the strong reference to the object. Each time you go through the loop, there's no longer any reference to the object created in the last iteration, and it is eligible for garbage collection.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

Objects are not garbage collected if they are reachable from a GC-root-object via strong references. In your example only one Test2-object is reachable from your thread at any time. The strong reference obj is updated each iteration and thus the previous Test2-object is no longer strongly referenced from anywhere and can be garbage collected.

If you want to create an OOM you might add the new objects to a List and keep them there.

shmosel
  • 49,289
  • 6
  • 73
  • 138
piet.t
  • 11,718
  • 21
  • 43
  • 52