| 1 | package com.hammurapi.store; |
| 2 | |
| 3 | import java.util.concurrent.TimeUnit; |
| 4 | import java.util.concurrent.atomic.AtomicInteger; |
| 5 | import java.util.concurrent.locks.Condition; |
| 6 | import java.util.concurrent.locks.Lock; |
| 7 | |
| 8 | /** |
| 9 | * Lock which acts on behalf of another lock and acquires its own lock only |
| 10 | * if the master lock is not held. This lock is used for executing one logical |
| 11 | * store operation in multiple threads. |
| 12 | * @author Pavel Vlasov |
| 13 | * |
| 14 | */ |
| 15 | public class DeputyLock implements TrackingLock { |
| 16 | |
| 17 | private Lock master; |
| 18 | private boolean masterLocked; |
| 19 | private AtomicInteger lockCounter = new AtomicInteger(0); |
| 20 | private boolean canNotBeLocked; |
| 21 | private String msg; |
| 22 | |
| 23 | public DeputyLock(Lock master, boolean masterLocked, boolean canNotBeLocked, String msg) { |
| 24 | this.master = master; |
| 25 | this.masterLocked = masterLocked; |
| 26 | this.canNotBeLocked = canNotBeLocked; |
| 27 | this.msg = msg; |
| 28 | } |
| 29 | |
| 30 | private void checkLockability() { |
| 31 | if (canNotBeLocked) { |
| 32 | throw new IllegalStateException(msg); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | @Override |
| 37 | public void lock() { |
| 38 | if (!masterLocked) { |
| 39 | checkLockability(); |
| 40 | master.lock(); |
| 41 | lockCounter.incrementAndGet(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | @Override |
| 46 | public void lockInterruptibly() throws InterruptedException { |
| 47 | if (!masterLocked) { |
| 48 | checkLockability(); |
| 49 | master.lockInterruptibly(); |
| 50 | lockCounter.incrementAndGet(); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | @Override |
| 55 | public boolean tryLock() { |
| 56 | if (masterLocked) { |
| 57 | return true; |
| 58 | } |
| 59 | checkLockability(); |
| 60 | if (master.tryLock()) { |
| 61 | lockCounter.incrementAndGet(); |
| 62 | return true; |
| 63 | } |
| 64 | return false; |
| 65 | } |
| 66 | |
| 67 | @Override |
| 68 | public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { |
| 69 | if (masterLocked) { |
| 70 | return true; |
| 71 | } |
| 72 | checkLockability(); |
| 73 | if (master.tryLock(time, unit)) { |
| 74 | lockCounter.incrementAndGet(); |
| 75 | return true; |
| 76 | } |
| 77 | return false; |
| 78 | } |
| 79 | |
| 80 | @Override |
| 81 | public void unlock() { |
| 82 | if (masterLocked) { |
| 83 | master.unlock(); |
| 84 | lockCounter.decrementAndGet(); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | public boolean isLocked() { |
| 89 | return masterLocked || lockCounter.get()>0; |
| 90 | } |
| 91 | |
| 92 | @Override |
| 93 | public Condition newCondition() { |
| 94 | return master.newCondition(); |
| 95 | } |
| 96 | |
| 97 | // public DeputyLock createDeputy() { |
| 98 | // return new DeputyLock(this, isLocked(), canNotBeLocked, msg); |
| 99 | // } |
| 100 | |
| 101 | } |