spring 多线操作事物问题 模拟

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SpringTransactionTest {

	
	ThreadLocal<String> threadLocal = new ThreadLocal<>();
	
	static ExecutorService executorService = Executors.newFixedThreadPool(4);
	 
	 
	 
	 public static void main(String[] args)throws Exception {
		final SpringTransactionTest springTransactionTest = new SpringTransactionTest();
		 
		/*for(int i=0;i<10;i++){
			 executorService.execute(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						springTransactionTest.updateDB();
					};
				});
		}
		Thread.sleep(10000);
		
		for(int i=0;i<10;i++){
			 executorService.execute(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						springTransactionTest.updateDB();
					};
				});
		}*/
		//并发执行数据库修改操作,线程池中,
		//每个线程对象持有数据库Connection对象在线程上下文中,没有释放。时间一久,会引起浪费,超时,等问题
		
		//解决办法 (推荐2)
		//1.手动释放线程上下文中的 数据库连接池对象connection
		//2.从设计角度上解决此问题,不要在线程池中获取数据库连接池
		
		
		
		for(int i=0;i<10;i++){
			 executorService.execute(new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						springTransactionTest.updateDB();
					};
				});
		}
		Thread.sleep(10000);
		
		for(int i=0;i<10;i++){
			 executorService.execute(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						springTransactionTest.updateDB();
					};
				});
		}
	}
	
	//执行数据库修改操作 (spring加事物)
	public void updateDB(){
		String threadId = Thread.currentThread().getId()+"";
		String connection = getConnection();
		System.out.println("threadId="+threadId+" connectionId="+connection);
		//update 
		
	}
	
	//获取数据库连接池 连接
	public String getConnection(){
		String connection = threadLocal.get();
		if(connection==null){
			threadLocal.set(UUID.randomUUID().toString());
		}
		return threadLocal.get();
	}
	
}

 

你可能感兴趣的:(spring 多线操作事物问题 模拟)