views:

105

answers:

1

I'm trying to understand the contract of drainPermits in the Java Semaphore class

The JavaDoc simply reads:

public int drainPermits()

Acquire and return all permits that are immediately available.

Returns:
    the number of permits

If no permits are currently available, does it block and wait until one is available?

+3  A: 

No, it will return 0 immediately. It doesn't require any permits to be available.

Jon Skeet
So if I am reviewing code where it looks like somebody might have been using it for locking, they're in for a nasty surprise, right?
Uri
It depends on exactly what they're doing. "Using it for locking" doesn't really give much of a hint.
Jon Skeet
if they are initializing it to 1 and using drain to implement a "tryAcquire" it is fine. In many different languages and systems, many implementations of a (non-nesting) mutex is a semaphore initialized to 1.
pgast