Java unlimited semaphore

2019-07-07 09:45发布

问题:

Wondering how to not limit connections (or anything) using a Semaphore.

So you might be thinking, "That sounds dumb." But, it simplifies my code a bit as it lets me treat the limited and unlimited cases uniformly.

Note I'm not looking for an advice on how to write something like

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

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

More specifically I'm looking for an Apache Commons or Java solution. This is just a simple situation in which I can write my own simple class to solve it, but when there are widely available utility solutions I prefer to use these.

回答1:

Given that Semaphore is a class, not an interface, you will be forced to have some form of branching in the logic. In order to avoid sprinkling "if (flag)" checks all around your code, you could create an interface for use in your application that includes the acquire and release semantics of the Semaphore class. From that point, provide two implementations, one that is essentially a no-op, providing no protection whatsoever, and another class that delegates to java.util.concurrent.Semaphore - from this point you are in a position to use dependency injection to determine which implementation to use.

Again, the branching inevitably has to live someplace, this just moves it up and out of the business logic.