Jorge Córdoba
Jorge Córdoba

Reputation: 52123

Does JVM garbage collector run when application shuts down?

I'm extremely confused about how finalizers work in the JVM regarding Garbage Collection from several sources here and around the internet.

It is my understanding, the usual approach is not to rely on finalizers to perform clean up as there's no guarantee about when they will be called or whether they would be called at all if the application finishes. However, I would still expect them to be called when the application finishes and all object cease to exist, as long as the application is alive.

In my particular case, I have an application with a class that opens a connection to another resource.

Simplified we will have

public class MyClass {

  Connection connection = new Connection();

  public MyClass() {
    connection.open();
  }

  public void close() {
    connection.close();
  }

  @Override
  protected void finalize() {
    connection.close();
  }
}

public class Main {
  public static void main(String[] args) {
    MyClass instance = new MyClass();

    // If I call instance.close(), application ends when it reaches end of main method
   // instance.close()

   // If not called, application will not end.

  }
}

Note the encapsulation purpose of "MyClass", the calling code does not necessarily need to know (nor does it need to) that he's using a non managed resource.

What happens is the application keeps running for ever, I assume hanged up on the open connection without ever releasing it since GC isn't called (and will never be called since there's no real memory pressure).

If the GC is not called when the application finishes, is there a way to guarantee the non managed resource (the connection) is closed when the application finishes? Obviously without having to explicitly call close.

I've seen the AutoClosable interface, and that is definitively an option but it still doesn't guarantee the connection will be eventually dropped when the application finishes.

Upvotes: 2

Views: 1245

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

If the GC is not called when the application finishes, is there a way to guarantee the non managed resource (the connection) is closed when the application finishes? Obviously without having to explicitly call close.

If you call (on Unix)

kill -9 {pid}

the process dies immediately without notifying the process. e.g no finally blocks are called. There is nothing you can do to prevent this.

You can enable to that finalizers are called on a graceful shutdown with runFinalizersOnExit but only on a graceful shutdown.

BTW If you pull out the power, or the network connection you won't have a graceful disconnect either, so you can't avoid needing to handle this, all you can do is cleanup on a graceful close()/shutdown.

Upvotes: 2

Related Questions