com.javajy.api.component.DBPool Maven / Gradle / Ivy
The newest version!
package com.javajy.api.component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DBPool {
private final String f;
private final String g;
private final String h;
private final List i;
private final List j = new ArrayList();
private final int k = 10;
private final int l = 20;
public DBPool(String var1, String var2, String var3) throws SQLException {
this.f = var1;
this.g = var2;
this.h = var3;
this.i = new ArrayList(10);
for(int var4 = 0; var4 < 10; ++var4) {
this.i.add(this.c());
}
}
public Connection getConnection() throws SQLException {
if (this.i.isEmpty()) {
if (this.j.size() >= 20) {
throw new SQLException("连接池已满");
}
this.i.add(this.c());
}
Connection var1 = (Connection)this.i.remove(this.i.size() - 1);
this.j.add(var1);
return var1;
}
public boolean releaseConnection(Connection var1) {
this.i.add(var1);
return this.j.remove(var1);
}
private Connection c() throws SQLException {
return DriverManager.getConnection(this.f, this.g, this.h);
}
public int getSize() {
return this.i.size() + this.j.size();
}
public void shutdown() throws SQLException {
this.j.forEach(this::releaseConnection);
Iterator var1 = this.i.iterator();
while(var1.hasNext()) {
Connection var2 = (Connection)var1.next();
var2.close();
}
this.i.clear();
}
// public static void main(String[] var0) throws Exception {
// String var1 = "jdbc:mysql://localhost:3306/mydatabase";
// String var2 = "root";
// String var3 = "password";
// DBPool var4 = new DBPool(var1, var2, var3);
// Connection var5 = var4.getConnection();
// var4.releaseConnection(var5);
// var4.shutdown();
// }
}