I have a Service that makes requests via a RestClient.
What is the Java best practice between:
- Opening and closing the connection every time I make a request
- Opening the connection at class initialization and closing it in a
ShutdownHook - Something I didn't think of
There are no "best practices". Please read and contemplate No Best Practices
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.
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.
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.