我发现当多个线程分别从 ComboPooledDataSource 的单个共享实例请求连接时,有时会从已在使用的池中返回连接。是否有配置设置或其他方法来确保当前签出的连接不会再次签出?
package stress;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
public class StressTestDriver
{
private static final String _host = "";
private static final String _port = "3306";
private static final String _database = "";
private static final String _user = "";
private static final String _pass = "";
public static void main(String[] args)
{
new StressTestDriver();
}
StressTestDriver()
{
ComboPooledDataSource cpds = new ComboPooledDataSource();
try
{
cpds.setDriverClass( "com.mysql.jdbc.Driver" );
String connectionString = "jdbc:mysql://" + _host + ":" + _port + "/"
+ _database;
cpds.setJdbcUrl( connectionString );
cpds.setMaxPoolSize( 15 );
cpds.setMaxIdleTime( 100 );
cpds.setAcquireRetryAttempts( 1 );
cpds.setNumHelperThreads( 3 );
cpds.setUser( _user );
cpds.setPassword( _pass );
}
catch( PropertyVetoException e )
{
e.printStackTrace();
return;
}
write("BEGIN");
try
{
for(int i=0; i<100000; ++i)
doConnection( cpds );
}
catch( Exception ex )
{
ex.printStackTrace();
}
finally
{
try
{
DataSources.destroy( cpds );
}
catch( SQLException e )
{
e.printStackTrace();
}
}
write("END");
}
void doConnection( final ComboPooledDataSource cpds )
{
Thread[] threads = new Thread[ 10 ];
final Set<String> set = new HashSet<String>(threads.length);
Runnable runnable = new Runnable()
{
public void run()
{
Connection conn = null;
try
{
conn = cpds.getConnection();
synchronized(set)
{
String toString = conn.toString();
if( set.contains( toString ) )
write("In-use connection: " + toString);
else
set.add( toString );
}
conn.close();
}
catch( Exception e )
{
e.printStackTrace();
return;
}
}
};
for(int i=0; i<threads.length; ++i)
{
threads[i] = new Thread( runnable );
threads[i].start();
}
for(int i=0; i<threads.length; ++i)
{
try
{
threads[i].join();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
private static void write(String msg)
{
String threadName = Thread.currentThread().getName();
System.err.println(threadName + ": " + msg);
}
}