A generic implementaion of a simple multi level lock.
The idea is to have an ascending number of lock levels ranging from 0
to maxLockLevel
as specified in {@link #GenericLock(Object,int,LoggerFacade)}: the higher the lock level the stronger and more restrictive the lock. To determine which lock may coexist with other locks you have to imagine matching pairs of lock levels. For each pair both parts allow for all lock levels less than or equal to the matching other part. Pairs are composed by the lowest and highest level not yet part of a pair and successively applying this method until no lock level is left. For an even amount of levels each level is part of exactly one pair. For an odd amount the middle level is paired with itself. The highst lock level may coexist with the lowest one (0
) which by definition means NO LOCK
. This implies that you will have to specify at least one other lock level and thus set maxLockLevel
to at least 1
.
Although this may sound complicated, in practice this is quite simple. Let us imagine you have three lock levels:
0
: NO LOCK
(always needed by the implementation of this lock) 1
: SHARED
2
: EXCLUSIVE
Accordingly, you will have to set
maxLockLevel
to
2
. Now, there are two pairs of levels
NO LOCK
with EXCLUSIVE
SHARED
with SHARED
This means when the current highest lock level is
NO LOCK
everything less or equal to
EXCLUSIVE
is allowed - which means every other lock level. On the other side
EXCLUSIVE
allows exacly for
NO LOCK
- which means nothing else. In conclusion,
SHARED
allows for
SHARED
or
NO LOCK
, but not for
EXCLUSIVE
. To make this very clear have a look at this table, where
o
means compatible or can coexist and
x
means incompatible or can not coexist:
| NO LOCK | SHARED | EXCLUSIVE |
NO LOCK | o | o | o |
SHARED | o | o | x |
EXCLUSIVE | o | x | x |
General limitations include:
- You are restricted to the scheme described above
- There are no preferences configurable for lock levels. This means whenever more than one party waits for a lock you can not specify which one is to be preferred. Under certain circumstances I might be nice to have the opportunity to give priority to parties either applying for higher or lower lock levels. It might even be desirable not only to give priority to higher or lower locks, but to a special level. For example you do not want to prefer higher lock levels, but exactly lock level
3
which might stand for WRITE
access. - It is not possible to represent hierarchical locks, i.e. locks having descendants that are locked whenever the lock itself is locked. Consequently, there also is no notion of an intention lock.
- You can not specify a timeframe for the validity of a lock. This means an owner of a thread can never lose a lock except when actively releasing it. This is bad when an owner either forgets to release a lock or is not able to do so due to error states or abnormal termination.
@version $Revision: 1.2 $