Proper way to try-catch a semaphore

后端 未结 2 1507
再見小時候
再見小時候 2021-01-14 09:35

What is the proper way to wrap semaphore actions in a try-catch block? What happens if the acquire action is interrupted after it has acquired some number, but not all, of

2条回答
  •  无人及你
    2021-01-14 10:05

    Take add method in BoundedHashSet for example,

        public boolean add(T o) throws InterruptedException {
            sem.acquire();
            boolean wasAdded = false;
            try {
                wasAdded = set.add(o);
                return wasAdded;
            } finally {
                if (!wasAdded)
                    sem.release();
            }
        }
    

    If sem.acquire(); throws InterruptedException, try block and finally block are skipped.

    Otherwise, we acquire the semaphore successfully, try block and finally block will be executed altogether. That is, we will release the same number of permits we have acquired.

提交回复
热议问题