Reputation: 167
I need a mutex in Java that provides exclusive access both within a single thread and across threads. Doing something very simple like this:
Lock l = new ReentrantLock();
for (int i = 0; i < 5; i++) {
Log.d(TAG, "Lock = " l.tryLock());
}
surprising gives me true for every call:
Lock = true
Lock = true
Lock = true
Lock = true
Lock = true
Why is this, or did I fundamentally something wrong?
Upvotes: 0
Views: 116
Reputation: 73568
As the name says it's re-entrant, meaning the owning thread can reacquire it.
This is a good thing, as otherwise you could easily create a single thread deadlock.
So no it does not act as a boolean semaphore. If you want a boolean semaphore, use new Semaphore(1);
. Although if you do intend to cause a self-deadlock, make sure you have another thread that can resolve it.
Upvotes: 1