Surendra Raut
Surendra Raut

Reputation: 370

Would below scenario cause a memory leak?

Would below scenario cause a memory leak?

Case 1

Here, I am not using new operator and so I am not sure how it works in Java when we do not user new operator and do assignment of object1 to object2.

public void doSomething() {
     String a1 = "Hello";
     String a2;

     while(true) {
         a2 = a1;
     }
 }

Case 2

Here,

public void doSomething() {
     String a1 = new String("Hello");
     String a2;

     while(true) {
         a2 = new String(a1);
     }
 }

Upvotes: 0

Views: 56

Answers (1)

weston
weston

Reputation: 54781

Case 1

You're not allocating any more memory, so you can't be leaking any. After one loop, variables a1 and a2 will reference the exact same single String instance.

Case 2

No, as it stands all the String instances you are creating will just be garbage collected, but you're not far off:

while(true) {
    a2 = new String(a1);
    a2.intern();
}

By placing the string in the PermGen (Permanent Generation) of the garbage collector, and then losing any references to it (in the next loop iteration) this would classify as a memory leak.

Upvotes: 1

Related Questions