package com.example.demo.hmjuc.day17;
import com.example.demo.hmjuc.Sleep;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.atomic.AtomicIntegerArray;
public class TestPool {
public static void main(String[] args) {
Pool pool = new Pool(2);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
Connection borrow = pool.borrow();
Sleep.sleep(new Random().nextInt(1000));
pool.free(borrow);
}).start();
}
}
}
class Pool {
private final Integer poolSize;
private Connection[] connections;
private AtomicIntegerArray statusArray;
public Pool(Integer poolSize) {
this.poolSize = poolSize;
this.connections = new Connection[poolSize];
this.statusArray = new AtomicIntegerArray(poolSize);
for (int i = 0; i < poolSize; i++) {
connections[i] = createConnection();
}
}
public Connection borrow() {
while (true) {
for (int i = 0; i < poolSize; i++) {
if (statusArray.get(i) == 0 && statusArray.compareAndSet(i, 0, 1)) {
return connections[i];
}
}
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void free(Connection conn) {
for (int i = 0; i < poolSize; i++) {
if (connections[i] == conn) {
statusArray.set(i, 0);
synchronized (this) {
this.notify();
}
break;
}
}
}
private Connection createConnection() {
Connection conn = null;
Properties props = new Properties();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
DriverManager.setLoginTimeout(10);
props.setProperty("user", "root");
props.setProperty("password", "root");
props.setProperty("remarks", "true");
props.setProperty("useInformationSchema", "true");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/delivery?serverTimezone=GMT%2B8&useSSL=false&useOldAliasMetadataBehavior=true&useUnicode=true&characterEncoding=utf8", props);
conn.setAutoCommit(true);
} catch (Exception e) {
e.printStackTrace();
close(conn);
}
return conn;
}
private static void close(Object obj) {
if (obj == null) {
return;
}
if (obj instanceof ResultSet) {
try {
((ResultSet) obj).close();
} catch (SQLException e) {
e.printStackTrace();
}
} else if (obj instanceof Statement) {
try {
((Statement) obj).close();
} catch (SQLException e) {
e.printStackTrace();
}
} else if (obj instanceof Connection) {
Connection c = (Connection) obj;
try {
if (!c.isClosed()) {
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}