Search code examples
javaredistry-with-resources

Java: Should we exit from try-with-resource block ASAP to release the resource?


Which of the below code snippet is better? Better in terms of handling resource.

try (Jedis jedis = jedisPool.getResource()) {
    String value = jedis.get("key");

    // Validation calls using `value` but not using `jedis`
    // Another DB call using `value` but not using `jedis`
}

OR

String value;
try (Jedis jedis = jedisPool.getResource()) {
    value = jedis.get("key");
}
// Validation calls using `value` but not using `jedis`
// Another DB call using `value` but not using `jedis`

In the first code snippet, the resource is held up until the other unrelated operations are completed whereas in the second it is being released as soon as it is used?


Solution

  • It's generally better to release resources as soon as possible. Especially if the next operation is a long one such as an access to a database. That way, the resource is released and is free to be used by other parts of your program.

    I'd consider holding on to the resource only if it's something expensive to create (e.g. a database connection) and there's a chance it will be needed again. However it seems that you're using a resource pool, so the resource creation cost will be rare. In a typical case the only cost would be some locking within the pool, which isn't that expensive in a properly written (and sized) pool.