brettwooldridge / HikariCP

光 HikariCP・A solid, high-performance, JDBC connection pool at last.
Apache License 2.0
19.65k stars 2.9k forks source link

Execute queries in seperate Threads #2129

Closed Placeblock closed 8 months ago

Placeblock commented 8 months ago

I have to execute some sql queries in seperate threads (probably from a thread pool). I read some other issues about multithreadding, however they did not help me much. What i know is that getConnection is not thread safe, so i cannot use getConnection in multiple threads. What i don't need is a single connection shared among many threads, but rather multiple threads using multiple connections from the pool. What should i do to execute my queries in seperate threads? Any help is welcome! Have a great day 😃

lfbayer commented 8 months ago

Have each thread individually call getConnection() (preferably with a try-with-resources block so that the connection is properly closed for each small set of work).

The getConnection method is absolutely thread safe, many threads can call this method simultaneously without problem. But what isn't thread safe is any connection returned by that method. So, ideally, you want those connection objects to be local variables within a block of code. At the very least don't use any specific connection from multiple threads. The thread using the connection should be the same threads as which called getConnection. Do not hold on to the connection for any significant amount of time. And absolutely call close on the connection when you are done with it. (try-with-resources is your friend here.)

https://github.com/brettwooldridge/HikariCP/issues/811#issuecomment-273734125