Explore the consequences of using the same database connection with multiple threads.

Source: Internet
Author: User

Explore the consequences of using the same database connection with multiple threads.

Seeing the connection pool useful to the database in the project, I thought about why the database connection pool is required and what is the impact of using only one connection pool? (Only use one connection )?

1. Conjecture: jdbc transactions are based on connection. If multiple threads share a connection, mutual interference may occur between transactions. (Connection. setAutoCommit (false); // connection. commit ())

2. Simulate the following scenario for a test:

Only one database connection is used for multi-user requests.

1) obtain the connection Tool class:

Package jdbcPool. util;

Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. SQLException;

Public class ConnectorUtil {

Public static final String user = "root ";

Public static final String pwd = "123456 ";

Public static final String driver = "com. mysql. jdbc. Driver ";

Public static final String url = "jdbc: mysql: // localhost: 3306/test ";

Private static Connection conn;

Private static int connectCount = 0;


Static {
Try {
Class. forName (driver );
} Catch (ClassNotFoundException e ){
System. out. println ("the database driver cannot be found ..");
E. printStackTrace ();
}
}

/**
* Getting database connection instances
* @ Return
*/
Public synchronized static Connection getInstance (){
If (conn = null ){
Try {
Conn = DriverManager. getConnection (url, user, pwd );
Conn. setAutoCommit (false); // set to not submit automatically...
ConnectCount ++;
System. out. println ("number of database connections:" + connectCount );
} Catch (SQLException e ){
System. out. println ("failed to connect to the database ....");
E. printStackTrace ();
}
}
Return conn;
}
}

 

2) Business interface implementation class:

Package jdbcPool. business;

Import java. SQL. Connection;
Import java. SQL. SQLException;
Import java. SQL. Statement;

Import jdbcPool. util. ConnectorUtil;

Public class StudentService {

Private Connection conn;

Private static StudentService studentService;


Private StudentService (){
Conn = ConnectorUtil. getInstance ();
}

Public static synchronized StudentService getInstance (){
If (studentService = null ){
StudentService = new StudentService ();
}
Return studentService;
}

Public void insert (String id, String name, String no) throws Exception {
String addStr = "insert into student (id, name, no) values ('" + id + "', '" + name + "', '" + no + "') ";
Statement statement = null;
Try {
Statement = conn. createStatement ();
Statement.exe cute (addStr );
If ("1350". equals (id) {// imitates a thread to execute a certain step of a service method. An exception occurs.
Thread. sleep (3000); // it takes a long time to simulate the current Thread .....
System. out. println ("exception ..... ");
System. out. println ("record" + id + "failed to insert .... ");
Conn. rollback (); // exception transaction rollback occurs...
Throw new Exception ();
} Else {
Conn. commit ();
System. out. println ("record" + id + "inserted successfully .... ");
}
} Catch (SQLException e ){
System. out. println ("failed to create statement ");
E. printStackTrace ();
} Finally {
If (statement! = Null ){
Try {
Statement. close ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}
}
}

}

3) thread classes simulating user requests:

Package jdbcPool. thread;

Import jdbcPool. business. StudentService;

Public class Request implements Runnable {

Private String id;


Public Request (String id ){
This. id = id;
}

@ Override
Public void run (){
// Simulates the service Singleton Mode
Try {
StudentService. getInstance (). insert (this. id, "name" + id, "no" + id );
} Catch (Exception e ){
E. printStackTrace ();
}
}
}

4) test class:

Package jdbcPool. test;
Import jdbcPool. thread. Request;


Public class Main {
// Two hundred threads concurrently access the same connection
Public static void main (String [] args ){
For (int I = 1300; I <1500; I ++ ){
Thread th = new Thread (new Request (String. valueOf (I )));
Th. start ();
}
}
}

 

5) Result Analysis:

Result of the printer:

Record 1489 inserted successfully ....
Record 1490 inserted successfully ....
Record 1491 inserted successfully ....
Record 1495 inserted successfully ....
Record 1492 inserted successfully ....
Record 1493 inserted successfully ....
Record 1494 inserted successfully ....
Record 1496 inserted successfully ....
Record 1497 inserted successfully ....
Record 1498 inserted successfully ....
Record 1499 inserted successfully ....
Record 1300 inserted successfully ....
Exception .....
Record 1350 insertion failed ....
Java. lang. Exception
At jdbcPool. business. StudentService. insert (StudentService. java: 38)
At jdbcPool. thread. Request. run (Request. java: 18)
At java. lang. Thread. run (Unknown Source)

Table data in the database:

 

Records with id 1350 are successfully added to the database.

When an exception occurs in the thread that adds a record with id 1350,

Other threads first call the connection. commit () method, so that the data that should not be submitted is submitted to the database.

6) Conclusion: In a multi-threaded environment, the use of a single connection will cause transaction confusion without thread security processing .... affects the use of jdbc transactions...

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.