Reputation: 370
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
Reputation: 54781
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.
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