Answer the question
In order to leave comments, you need to log in
JDBC, why can't one Connection be used for several methods in the context of multithreading?
Create a class variable
private Connection connection;
// Initialize it in the constructor
private myManager() {
String connectionUrl = getConnectionUrl();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(connectionUrl);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
Answer the question
In order to leave comments, you need to log in
1. Synchronization between threads. If both threads start sending requests to the database through one connection, special effects may begin (here you need to smoke the "thread safety" of the connection)
2. Transactions in the database. Requests through one connection will be in one transaction. If it's OK for you, then it's OK. If different threads require different transactions, then each thread will have to issue its own connection.
100 users and 100 threads are slightly different things. First of all, I would look here - the flow per user looks suspicious to me. If this is a web, then you receive a request from each user, it is processed, and a response is sent. All. If few requests come from users, one thread can do it. And even in the case of websockets, you still don't need to keep a stream per user.
You can use it, but you need to do synchronization between different ceilings.
The problem is that one thread will wait for a response to its request, while another thread wants to fulfill its request.
So, if you add synchronization, then you can.
But in general, you don’t need to reinvent the wheel, use connection pools, there are many different ones.
For example hikaricp https://habr.com/en/post/269023/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question