并未考虑动态扩容与收缩,可用性检测,超时等待
public class Test {
@SneakyThrows
public static void main(String[] args) {
Pool pool = new Pool(2);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
Connection connection = pool.getConnection();
try {
Thread.sleep(new Random().nextInt(2));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
pool.free(connection);
}, String.valueOf(i)).start();
}
}
}
@Slf4j(topic = "c.Pool")
class Pool {
private static int poolSize;
private static Connection[] connections;
private static AtomicIntegerArray states;
public Pool(int poolSize) {
this.poolSize = poolSize;
connections = new Connection[poolSize];
for (int i = 0; i < poolSize; i++) {
connections[i] = new MockConnection("Connection -> " + i);
}
states = new AtomicIntegerArray(poolSize);
}
public Connection getConnection() {
while (true) {
for (int i = 0; i < poolSize; i ++) {
if (states.get(i) == 0) {
if (states.compareAndSet(i, 0, 1)) {
log.debug("getConnection -> {}", i);
return connections[i];
}
}
}
synchronized (this) {
try {
log.debug("wait");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void free(Connection connection) {
for (int i = 0; i < poolSize; i ++) {
if (connection == connections[i]) {
states.set(i, 0);
log.debug("free -> {}", i);
synchronized (this) {
this.notifyAll();
log.debug("notifyAll {}", i);
}
break;
}
}
}
}
class MockConnection implements Connection{
private String name;
public MockConnection (String name) {
this.name = name;
}
}