Home > Enterprise >  Should I keep JDBC connection alive?
Should I keep JDBC connection alive?

Time:06-29

Im developing a discord bot using JDA and within this discord bot there are commands which require access to the database to insert or delete or update records, now there are many of these commands so when the discord server is at its peak, a lot of connections may be required.

My question is: Should I open a connection and leave it open (singleton) and just call the connection whenever I want to use it reconnect whenever it dies (server side timeout)? Or connect , execute, and finally close?

Thank you very much!

CodePudding user response:

Especially for multithreaded applications it is worth thinking about that. A connection is costly, mostly for the context on the database side. So for performance reasons you might want to keep the connection.

But a connection is still costly, and you do not want to open too many of them in parallel as that can impact performance also.

That's why multithreaded applications keep a number of connections open but the threads do not hog each one of the connections. Instead they take one from a pool, use it and return it afterwards. It is the connection pool that decides how many connections need to be opened or closed.

To not reinvent the wheel, check out database connection pool implementations such as Apache Commons DBCP.

  • Related