简体   繁体   中英

Should I keep JDBC connection alive?

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM