javashutdown-hook

Is shutdown-hook a good practice?


I have a Service that makes requests via a RestClient.

What is the Java best practice between:

  1. Opening and closing the connection every time I make a request
  2. Opening the connection at class initialization and closing it in a ShutdownHook
  3. Something I didn't think of

Solution

  • What is the Java best practice between

    There are no "best practices". Please read and contemplate No Best Practices

    1. Opening and closing the connection every time I make a request

    That's inefficient, especially if you are talking to an HTTPS endpoint.

    Also, if you accidentally fail to close the connection, there is a potential that you will leak resources. It depends on how you open the connection.

    1. Opening the connection at class initialization and closing it in a ShutdownHook.

    OK but, don't need to close it in a shutdown hook. All of your application's outstanding network connections will be closed by the operating system when your application exits. Closing them explicitly is unnecessary.

    1. Something I didn't think of ...

    a. Open the connection once at the start (in class initialization, via a singleton, whatever) ... and don't bother to close it. (See above.)

    b. Use an HTTP client or REST client library that can manage a connection pool. Especially if your application is multi-threaded, or if it talks to multiple HTTP or HTTPS endpoints.