[concurrency-interest] Custom Lock

Luís Matta levmatta@uol.com.br
Wed, 7 Jan 2004 23:25:30 -0200


Hello all,
    I felt pressured, so I'm releasing a prototype of a Lock that does
priority invertion.
Please consider, only, the algoritm and what I had to do to get to it.
One can find about priority invertion in Silberschatz (problably Tanenbaum)
or any book about
realtime (including Real Time Java spec). It's fundemental, specially if you
have threads with differente
priorities competing for the same resource (than it's a must have).


        private final AtomicInteger priority = new
AtomicInteger(Thread.MIN_PRIORITY);

        private AtomicReference<Thread> owner = new
AtomicReference<Thread>();

        public int acquireExclusiveState(boolean isQueued, int acquires) {
            Thread curr = Thread.currentThread();
            assert acquires == 1; // Does not use multiple acquires
            int result = state().compareAndSet(0, 1)? 0 : -1;
            if (result>-1){//thread safe (reentrant) code inside here (if
threads were corrected)
                priority.set(curr.getPriority());//there is not a big care
about this value
                owner.set(curr);//you may notice that I never reset owner to
null
            }else{
                synchronized(this){
                    int pri = curr.getPriority();
                    int delta = pri - priority.get();
                    if (delta>0){
                        curr.setPriority(pri+delta);
                    }
                }
            }
            return result;
        }

        public boolean releaseExclusiveState(int releases) {
            boolean result = state().compareAndSet(1,0);
            if (result){//thread safe (reentrant) code inside here (if
threads were corrected)

owner.get().setPriority(priority.getAndSet(Thread.MIN_PRIORITY));
                //if this value is inapropriate then it will be corrected by
other locks
                //if it isn't corrected then it should be greater than the
original
                //(I'm not making a big fuss because for a proper
implementation I need better API support)
            }
            return result;
        }

Why my needs are not meat: (although I'm not going to use the code above)
    - There are pleanty compareAndSets or incAnd.. or decAnd, but no
ifgreaterSet, ifsmallerSet and so on
       (I have no ideia if theres is atomic opcodes for these operations)
    - AbstractQueuedSynchronizer doesn't hold its owner (and I did a terible
job trying)
    - Thread has no atomic operation with its Priority, maybe someone has te
influence to add this (preferably using my first proposal)
    - no control over the Queu, please insert a non final class for the Queu
node, so people can add behavior to it
       (and a field to hold the queu node class so you can use it, in your
final methods)

Thanks every one.
Luis

PSA: I would like to see a owned Lock example using
AbstractQueuedSynchronizer, anyone??