    001package com.hammurapi.store;
    002
    003import java.util.concurrent.TimeUnit;
    004import java.util.concurrent.locks.Condition;
    005import java.util.concurrent.locks.Lock;
    006
    007/**
    008 * This class tracks number of locks acquired by current thread.
    009 * @author Pavel Vlasov
    010 *
    011 */
    012public abstract class AbstractTrackingLock implements TrackingLock {
    013
    014        protected abstract void incCounter();
    015        protected abstract void decCounter();
    016        protected abstract int getCounter();
    017
    018        private Lock master;
    019
    020        public boolean isLocked() {
    021                return getCounter()>0;
    022        }
    023
    024        public AbstractTrackingLock(Lock master) {
    025                this.master = master;
    026        }
    027
    028        @Override
    029        public void lock() {
    030                master.lock();
    031                incCounter();
    032        }
    033
    034        @Override
    035        public void lockInterruptibly() throws InterruptedException {
    036                master.lockInterruptibly();
    037                incCounter();
    038        }
    039
    040        @Override
    041        public boolean tryLock() {
    042                if (master.tryLock()) {
    043                        incCounter();
    044                        return true;
    045                }
    046                return false;
    047        }
    048
    049        @Override
    050        public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
    051                if (master.tryLock(time, unit)) {
    052                        incCounter();
    053                        return true;
    054                }
    055                return false;
    056        }
    057
    058        @Override
    059        public void unlock() {
    060                master.unlock();
    061                decCounter();
    062        }
    063
    064        @Override
    065        public Condition newCondition() {
    066                return master.newCondition();
    067        }
    068
    069}