0

I was reading about Java's garbage collection here and here. I still have two questions.

  1. Suppose I have the following class

    public final class Employee {
    
    private final String empID;
    private final String empFirstName;
    private final String empLastName;
    
    public Employee(String ID, String Firstname, String Lastname)
    {
        this.empID = ID;
        this.empFirstName = Firstname;
        this.empLastName = Lastname;
    
    }
    
    public String getEmpID() {
        return empID;
    }
    
    public String getEmpFirstName() {
        return empFirstName;
    }
    
    public String getEmpLastName() {
        return empLastName;
    }
    

and I add my employee objects to an ArrayList.

List<Employee> empList = new ArrayList<Employee>();

empList.add(new Employee("1", "Sally","Solomon"));
empList.add(new Employee("2", "Harry","Solomon"));

Now, if I were to call System.exit(0) right after the last employee object was inserted, when does the GC run to free up memory?

  1. In one of the links provided it talks about GC and static variables. I'm a little new to the GC concept, and a a little confused. The link says that static variables will not be garbage collected. How do you free up memory when using static variables? Will the memory be freed when the application is closed?
Community
  • 1
  • 1

1 Answers1

3

if I were to call System.exit(0) right after the last employee object was inserted, when does the GC run to free up memory?

When the JVM exits, it doesn't need to run its own garbage collector in order to free up memory. The operating system reclaims the process' memory when the process exits.

This isn't something specific to the JVM.

How do you free up memory when using static variables?

You can null out, or otherwise remove references to, those static objects. There are some other possibilities as well: Are static fields open for garbage collection?

Will the memory be freed when the application is closed?

Yes, but not necessarily by the JVM's GC. The OS takes care of it – that's part of its job.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710