Opening a database connection in a constructor, wh

2020-06-25 03:55发布

问题:

well, I've been thinking of making database requests a little faster by keeping the connection to the database open as long as the object is being used. So I was thinking of opening the connection in the constructor of that class. Now the question is, how can I close the connection after I stopped using? I have to call close() somewhere, don't I? I've been reading about the finalize() method, but people seemed to be skeptical about usage of this method anywhere at all. I'd expect it to have something like a destructor, but Java doesn't have that, so?

So could anyone provide me with a solution? Thanks in advance.

回答1:

I would suggest that you rather implement database connection pooling if the application would allow it. With connection pooling a pool of connections would be created and stay connected to the database. Your application would then grab a open/unused connection from the pool use it and return it to the pool.

This would allow you to acquire connections faster and you won't have to modify your classes too much. Database connection pooling is a great technique if you need to scale your application.

The other benefit is that your database connection pool will be managed by some sort of driver which will take care of opening connections, keeping them open, growing the pool if required and also shrinking the pool when extra connections are not used for a certain amount of time. This would be similar to the code you are trying to implement in the constructor and finalization methods.

Generally speaking you aqquire a database connection only when needed and release it as soon as possible.



回答2:

I would recommend to make your class an implementor of java.io.Closeable. According to this interface you will have to implement void close() throws IOException, which all clients of the class will call, because it's a good practice to close Closeable classes after use.