In a practical application scenario, when a connection pool is created, the maximum number of connections is set. How does a connection pool control the number of threads that only have the maximum number of connections to fetch connection objects?

/** * Use semaphores to limit the flow of the object pool, that is, only N threads can access the object pool at the same time */
public class ObjectPool {

    final List<Object> pool;
    // Implement current limiter with semaphore
    final Semaphore sem;

    // constructor
    ObjectPool(int size) {
        // Vector is a thread-safe list
        pool = new Vector<Object>();
        // Create size objects to add to the object pool
        for (int i = 0; i < size; i++) {
            pool.add(new Object());
        }
        sem = new Semaphore(size);
    }

    // Call func using objects from the object pool
    @SneakyThrows
    String exec(Function<Object, String> func) {
        Object t = null;
        sem.acquire();
        try {
            t = pool.remove(0);
            return func.apply(t);
        } finally{ pool.add(t); sem.release(); }}public static void main(String[] args) {

        // Create an object pool
        ObjectPool pool =new ObjectPool(10);
        // The pool of objects executes exec(), which allows up to size threads to execute func.apply()
        //sem.acquire();
        for (int i = 0; i < 11; i++) {
            new Thread(() -> pool.exec(t -> {
                System.out.println(t);
                returnt.toString(); })).start(); }}}Copy the code