-5

Would this Java code result in memory leak

class Employee {
    Person person;

    Employee() {}

    String getPersonGender(String name) {
        this.person = new Person(name);
        return person.getGender().toString();
    }
}

public static void main(String... args) {
    Employee e;

    String gender = e.getPersonGender("James"); // First Time
    String gender = e.getPersonGender("Merry"); // Second Time 
}

When from the main, we call getPersonGender for the 2nd time, would the Person object created the first time be available for garbage collected to free up?

Or would both Person object would be freed up only when we exit the main function?

Harman
  • 1,571
  • 1
  • 19
  • 31
  • 2
    This is just a class definition. On its own, it does not execute anything. – Anis R. May 07 '19 at 01:02
  • Handle what? What do you think is abnormal here and why? – Sotirios Delimanolis May 07 '19 at 01:04
  • Edited the question to make it more clearer. – Harman May 07 '19 at 01:12
  • That code will throw a NullPointerException and won't compile since you're declaring gender twice. Please post **real** code. But regardless, your main question appears to be "when are objects available for GC", and I recommend that you read the canonical question and its answer for that. – Hovercraft Full Of Eels May 07 '19 at 01:15
  • So replacing a variables reference *may* allow the prior object to be GC'd, but it's never that simple since the original object may still be used elsewhere even if the original variable refers to a new object. – Hovercraft Full Of Eels May 07 '19 at 01:17
  • @HovercraftFullOfEels You said it may allow the prior object to be GC'd. Can you elaborate on that? Under what conditions would it be GC'd vs not be GC'd? – Harman May 07 '19 at 01:21
  • [link](https://stackoverflow.com/questions/13144899/when-is-the-object-eligible-for-garbage-collection) – Hovercraft Full Of Eels May 07 '19 at 01:22
  • This code does not compile as `e` is not initialized. If you initialize `e` with an instance of `Employee`, it is still possible that this instance gets garbage collected and in turn, any `Person` instance referenced by it, as local variables do not prevent garbage collection per se. It’s an implementation detail whether this actually may happen. Since this code does noting useful (has no perceivable effect), an optimizer may even eliminate it completely, not creating any object at all. – Holger May 07 '19 at 08:28

1 Answers1

-2

No. A memory leak is a failure in a program to release discarded memory, causing impaired performance or failure.

As Anis R. said, your code does execute anything independently. However, if you were to make ridiculously large amounts of Employee type variables, that would be able to cause a memory leak. Correct me if I am wrong.

FailingCoder
  • 757
  • 1
  • 8
  • 20