V
V
Valeriy_Morozov2022-01-16 03:07:39
Java
Valeriy_Morozov, 2022-01-16 03:07:39

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();
        }

    }


And we use it for all CRUD operations in the class.
I understand that it's so bad, but I want to understand why it is in the context of multithreading
1. What's bad will happen if two threads simultaneously access the connection?
2. Won't each of the threads have its own connection instance, we don't create it static? Accordingly, two threads cannot access the same instance.
3. The database is very limited in terms of the number of connections, how it works when there are 100 users of the program (it turns out that 100 threads with their connections will access it).

I will be very grateful for the answers, especially to question 2.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2022-01-18
@Valeriy_Morozov

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.

A
Alexey Cheremisin, 2022-01-16
@leahch

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 question

Ask a Question

731 491 924 answers to any question