How and why can a Semaphore give out more permits than it was initialized with?

前端 未结 6 1298
庸人自扰
庸人自扰 2021-02-08 12:18

I am reading the book Java Concurrency in Practice. In a section about java.util.concurrent.Semaphore, the below lines are present in the book. It is a comment abou

6条回答
  •  礼貌的吻别
    2021-02-08 13:00

    It is surprising to some of us.

    You can easily subclass up a bounded semaphore.

    /**
     * Terrible performance bounded semaphore.
     **/
     public class BoundedSemaphore extends Semaphore {
        private static final long serialVersionUID = -570124236163243243L;
        final int bound;
        public BoundedSemaphore(int permits) {
            super(permits);
            bound=permits;
        }
    
        @Override
        synchronized public void acquire() throws InterruptedException {
            super.acquire();
        }
    
        @Override
        synchronized public boolean tryAcquire() {
            return super.tryAcquire();
        }
    
        @Override
        synchronized public void release() {
            if( availablePermits()

提交回复
热议问题