2

I'm writing an adapter for redission client to use in our application, I'm not sure if it is a good design to close the client in the finalize block. Below is the code. Please let me know

private static final RedissonClient client;

static {
    File configFile = Paths.get(Constants.ConfigDir, "cache- 
config.yml").toFile();
    try {
        client = Redisson.create(Config.fromYAML(configFile));
    } catch (IOException e) {
        throw new UnableToCreateCacheClientException(e.getMessage() + e.getStackTrace(), e.getCause());
    }
}

@Override
protected void finalize() throws Throwable {
    super.finalize();
    client.shutdown();
}

public static RedissonClient getClient() {
    return client;
}

EDIT : I'm interested in knowing the right design to close a static final connection object in a web app. I cannot close it in a finally block of a method because the client will be used by multiple methods in multiple classes

BeingVikram
  • 33
  • 2
  • 5
  • Possible duplicate of [Clean up code in finalize() or finally()?](https://stackoverflow.com/questions/1843905/clean-up-code-in-finalize-or-finally) – CannedMoose Apr 27 '18 at 05:27

1 Answers1

1

You shouldn't rely on the finalize() method shutting down the client - you should be sure to close it elsewhere. finalize() will only get called when the object is garbage collected, which may be long after the client should have been shutdown (and may be never, depending on the lifecycle of the program and gc options.)

For this reason many will just get rid of the finalize() method entirely.

If you do leave it there, then just treat it as a backup to catch a coding error upstream. First check if the client is shutdown, and if not, make sure there's a warning message printed that indicates you've got a bug that you need to solve!

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • The only other place I know where i can close the client is the contextDestroyed method of the ServletContextListener. In [this](https://stackify.com/memory-leaks-java/) article the author says the static objects are linked to the lifecycle of the JVM. I wanted to tie the client object to the lifecycle of my web app not to the lifecycle of the JVM – BeingVikram Apr 27 '18 at 17:42