woieha320r的博客

享元

用于将高频创建的对象重复利用,比如连接池、线程池

· 将可能被频繁重复创建的对象交给工厂负责提供/回收,工厂在初始化时就使用缓存池缓存一定数量的实例并对外提供

import lombok.AllArgsConstructor;

import java.util.Stack;

@AllArgsConstructor
class Connection {
    private final String url;
    private final String username;
    private final String password;
}

public class ConnectionPoolFlyweight {
    private static final int POOL_SIZE = 10;
    private static final int WAIT_MILLISECONDS = 3000;
    private static final Stack<Connection> POOL = new Stack<>();

    static {
        for (int i = 0; i < POOL_SIZE; i++) {
            POOL.push(new Connection("localhost:2023", "root", "123456"));
        }
    }

    public static Connection getConnection() throws InterruptedException {
        if (POOL.isEmpty()) {
            Thread.sleep(WAIT_MILLISECONDS);
            return getConnection();
        }
        return POOL.pop();
    }

    public static void releaseConnection(Connection connection) {
        POOL.push(connection);
    }
}