public class Mutex extends CObject implements Sync
This class implements a mutual exclusion scheme between threads.
The correct algorithm pattern to use Mutex objects should use try/finally
blocks:
mtx.lock(); try { ... } finally { mtx.unlock(); }
This class follows DbC(tm) methodology
(Wikipedia).
Where possible, contracts are implement with native's Java
assert.
Modifier and Type | Class and Description |
---|---|
static class |
Mutex.Priority
Locking priority choices:
UNDEFINED: undefined priority (default); TIME_OF_ARRIVAL: priority ordered by decreasing waiting time (not yet implemented!). |
Constructor and Description |
---|
Mutex()
Constructs a new non-recursive Mutex with UNDEFINED priority and registering waiting threads.
|
Mutex(boolean recursive)
Constructs a new Mutex with UNDEFINED priority and registering waiting threads.
|
Mutex(boolean recursive,
boolean registerAwaitingThreads)
Constructs a new Mutex with UNDEFINED priority.
|
Modifier and Type | Method and Description |
---|---|
SyncState |
getStateAndUnlock()
Get current Sync state, and unlock it (if applicable).
|
void |
lock()
Locks mutex.
|
int |
lockCount()
Lock count of current mutex.
|
boolean |
lockIsMine()
Is lock owned by me?
|
MutexCV |
newCV()
Create and return a new condition variable attached to current Mutex.
|
void |
recoverState(SyncState state)
Recover Sync state.
|
boolean |
recursive()
Is current mutex recursive?
|
boolean |
trylock()
Try to lock mutex (without waiting).
|
void |
unlock()
Unlocks mutex.
|
await, await, await, broadcast, interruptWaitingThreads, registerAwaitingThreads, signal, syncronizedLockIsMine
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
interruptWaitingThreads, registerAwaitingThreads
public Mutex()
public Mutex(boolean recursive)
recursive
- if true, the created mutex will be recursive (non-recursive, if false)public Mutex(boolean recursive, boolean registerAwaitingThreads)
recursive
- if true, the created mutex will be recursive (non-recursive, if false)registerAwaitingThreads
- if true, threads are registered when waitingpublic void lock()
!lockIsMine() || recursive()
- not own lock unless if recursivelockIsMine()
- lock is minepublic boolean trylock()
!lockIsMine() || recursive()
- not own lock unless if recursiveresult && lockIsMine() || !result && !lockIsMine()
public void unlock()
lockIsMine()
!lockIsMine() || lockCount() > 0
public boolean lockIsMine()
CObject
lockIsMine
in interface Sync
lockIsMine
in interface SyncCV
lockIsMine
in class CObject
public boolean recursive()
public int lockCount()
lockIsMine()
public MutexCV newCV()
public SyncState getStateAndUnlock()
Sync
lockIsMine()
getStateAndUnlock
in interface Sync
public void recoverState(SyncState state) throws ThreadInterruptedException
Sync
state != null && state.obj() == this
- my state object required!lockIsMine()
recoverState
in interface Sync
state
- Sync state object (returned by getStateAndUnlock)ThreadInterruptedException