| 1 | package com.hammurapi.store; |
| 2 | |
| 3 | import java.util.concurrent.TimeUnit; |
| 4 | import java.util.concurrent.locks.Condition; |
| 5 | import java.util.concurrent.locks.Lock; |
| 6 | |
| 7 | /** |
| 8 | * This class tracks number of locks acquired by current thread. |
| 9 | * @author Pavel Vlasov |
| 10 | * |
| 11 | */ |
| 12 | public abstract class AbstractTrackingLock implements TrackingLock { |
| 13 | |
| 14 | protected abstract void incCounter(); |
| 15 | protected abstract void decCounter(); |
| 16 | protected abstract int getCounter(); |
| 17 | |
| 18 | private Lock master; |
| 19 | |
| 20 | public boolean isLocked() { |
| 21 | return getCounter()>0; |
| 22 | } |
| 23 | |
| 24 | public AbstractTrackingLock(Lock master) { |
| 25 | this.master = master; |
| 26 | } |
| 27 | |
| 28 | @Override |
| 29 | public void lock() { |
| 30 | master.lock(); |
| 31 | incCounter(); |
| 32 | } |
| 33 | |
| 34 | @Override |
| 35 | public void lockInterruptibly() throws InterruptedException { |
| 36 | master.lockInterruptibly(); |
| 37 | incCounter(); |
| 38 | } |
| 39 | |
| 40 | @Override |
| 41 | public boolean tryLock() { |
| 42 | if (master.tryLock()) { |
| 43 | incCounter(); |
| 44 | return true; |
| 45 | } |
| 46 | return false; |
| 47 | } |
| 48 | |
| 49 | @Override |
| 50 | public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { |
| 51 | if (master.tryLock(time, unit)) { |
| 52 | incCounter(); |
| 53 | return true; |
| 54 | } |
| 55 | return false; |
| 56 | } |
| 57 | |
| 58 | @Override |
| 59 | public void unlock() { |
| 60 | master.unlock(); |
| 61 | decCounter(); |
| 62 | } |
| 63 | |
| 64 | @Override |
| 65 | public Condition newCondition() { |
| 66 | return master.newCondition(); |
| 67 | } |
| 68 | |
| 69 | } |