一、连接池接口
public interface MyPool {
Connection getConnection(long overtime) throws InterruptedException;
void releaseConn(Connection connection);
}
二、连接池实现类
public class MyDbPool implements MyPool {
//连接对象容器
private static LinkedList<Connection> pool = new LinkedList<>();
public MyDbPool(int capacity) {
if (capacity > 0) {
for (int i = 0; i < capacity; i++) {
pool.addLast(new MyConnectionImpl());
}
}
}
@Override
public Connection getConnection(long overtime) throws InterruptedException {
synchronized (pool) {
if (overtime < 0) {
while (pool.isEmpty()) {
pool.wait();
}
return pool.removeFirst();
} else {
long end = System.currentTimeMillis() + overtime;
long remain = overtime;
while (pool.isEmpty() && remain > 0) {
pool.wait(remain);
remain = end - System.currentTimeMillis();
}
Connection conn = null;
if (!pool.isEmpty()) {
conn = pool.removeFirst();
}
return conn;
}
}
}
@Override
public void releaseConn(Connection connection) {
if (connection != null) {
synchronized (pool) {
pool.addLast(connection);
pool.notifyAll();
}
}
}
}
三、连接实现类
public class MyConnectionImpl implements Connection {
@Override
public Statement createStatement() throws SQLException {
SleepTools.ms(1);
return null;
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return null;
}
@Override
public String nativeSQL(String sql) throws SQLException {
return null;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
}
@Override
public boolean getAutoCommit() throws SQLException {
return false;
}
@Override
public void commit() throws SQLException {
SleepTools.ms(50);
}
@Override
public void rollback() throws SQLException {
}
@Override
public void close() throws SQLException {
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return null;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
}
@Override
public boolean isReadOnly() throws SQLException {
return false;
}
@Override
public void setCatalog(String catalog) throws SQLException {
}
@Override
public String getCatalog() throws SQLException {
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
}
@Override
public int getTransactionIsolation() throws SQLException {
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
}
@Override
public void setHoldability(int holdability) throws SQLException {
}
@Override
public int getHoldability() throws SQLException {
return 0;
}
@Override
public Savepoint setSavepoint() throws SQLException {
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return null;
}
@Override
public Clob createClob() throws SQLException {
return null;
}
@Override
public Blob createBlob() throws SQLException {
return null;
}
@Override
public NClob createNClob() throws SQLException {
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
return false;
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public String getClientInfo(String name) throws SQLException {
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
return null;
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
@Override
public void setSchema(String schema) throws SQLException {
}
@Override
public String getSchema() throws SQLException {
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
}
@Override
public int getNetworkTimeout() throws SQLException {
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
四、测试类
public class MyDbPoolTest {
private static CountDownLatch end;
private static MyPool myPool = new MyDbPool(25);
public static void main(String[] args) throws InterruptedException {
int numOfThread = 50;
end = new CountDownLatch(numOfThread);
int times = 20;
AtomicInteger success = new AtomicInteger();
AtomicInteger failed = new AtomicInteger();
for (int i = 0; i < numOfThread; i++) {
new Thread(new MyWorker(success, failed, times), "Worker_" + i).start();
}
end.await();
System.out.println("总尝试次数:" + numOfThread * times);
System.out.println("成功次数:" + success);
System.out.println("失败次数:" + failed);
}
private static class MyWorker implements Runnable {
private AtomicInteger success;
private AtomicInteger failed;
private int times;
public MyWorker(AtomicInteger success, AtomicInteger failed, int times) {
this.success = success;
this.failed = failed;
this.times = times;
}
@Override
public void run() {
while (times > 0) {
try {
Connection connection = myPool.getConnection(1000);
if (connection != null) {
try {
connection.createStatement();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
myPool.releaseConn(connection);
success.incrementAndGet();
}
} else {
System.out.println("线程" + Thread.currentThread().getName() + "获取连接失败!");
failed.incrementAndGet();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
times--;
}
}
end.countDown();
}
}
}