7

Hi I am new in implementing the java code, Tried the following things:-

I am using jedis as redis java client-library, I have made the jedis object and used its api to print the redis information, but this all is done inside the method, So my doubt is "should I use jedis.close() to close the client connection in my code"

    class Information{

        public void redisdetails(){

        Jedis jedis = new Jedis("localhost", 6379));

                Map<String, Object> info = new HashMap<>();

                info.put("server", jedis.info("server"));
                info.put("memory", jedis.info("memory"));
                info.put("clients", jedis.info("clients"));
                info.put("stats", jedis.info("stats"));


        }
}

because the jedis object is been created inside the redisdetails method, so object will automatically destroyed or i need to write jedis.close() and if yes then why?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Rohit Pathak
  • 71
  • 1
  • 3
  • 5
    You have to close the jedis object. If you don't close it doesn't release back to pool and you can't get a new resource from pool. Jedis implements Closeable interface, so if you use try-with-resources you don't have to close it yourself. – nbokmans Feb 27 '19 at 09:44
  • 3
    "because the jedis object is been created inside the redisdetails method, so object will automatically destroyed" - no, it won't get automatically destroyed. The reference would get destroyed but the object itself would remain on the heap and _might_ get garbage collected at some point (no guarantees there) and even if it is you can't be certain the `finalize()` method would be called which would be the only point where you could implement some auto-close upon gc. - Thus in Java always close any resource you don't need anymore. – Thomas Feb 27 '19 at 09:45
  • @Thomas Thank you ! your answer cleared my doubt. – Rohit Pathak Feb 27 '19 at 09:50
  • @nbokmans Thank you ! – Rohit Pathak Feb 27 '19 at 09:52

0 Answers0