Search code examples
javastaticfinalizeredisson

Redisson: Closing client in finalize method


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


Solution

  • 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!