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

前端 未结 6 1293
庸人自扰
庸人自扰 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:15

    Instead of "handing out" permit objects, the implementation just has a counter. When a new permit is "created" the counter is increased, when a permit is "returned" the counter is decreased.

    This makes for much better performance than creating actual objects all the time.

    The tradeoff is that the Semaphore itself cannot detect certain kinds of programming errors (such as unauthorized permit cash-ins, or semaphore leaks). As the coder, you have to make sure to follow the rules on your own.

提交回复
热议问题