Java unlimited semaphore

Think about how not to restrict connections (or anything) with Semaphore.

So you might think, "That sounds stupid." But, this simplifies my code a bit, as it allows me to treat limited and unlimited cases evenly.

Note. I am not looking for advice on how to write something like

if(limited) { semaphore.acquire(); } 

I can come up with dozens of ways to do this with if statements.

In particular, I'm looking for Apache Commons or a Java solution. This is just a simple situation where I can write my own simple class to solve it, but when there are widely available utilities, I prefer to use them.

+3
source share
1 answer

Given that Semaphore is a class, not an interface, you will be forced to have some kind of branch in the logic. To avoid splashing "if (flag)", it checks everything around your code, you can create an interface for use in your application that includes the semantics of acquiring and releasing the Semaphore class. From now on, you will get two implementations that are essentially not operational, that do not provide any protection, and another class that delegates to java.util.concurrent.Semaphore - from now on you can use dependency injection to determine which implementation to use.

Again, branching inevitably has to live somewhere, it just moves it and leaves the business logic.

+1
source

All Articles