package com.hammurapi.store;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * This class tracks number of locks acquired by current thread.
 * @author Pavel Vlasov
 *
 */
public abstract class AbstractTrackingLock implements TrackingLock {
	
	protected abstract void incCounter();
	protected abstract void decCounter();
	protected abstract int getCounter();
	
	private Lock master;
	
	public boolean isLocked() {
		return getCounter()>0;
	}
	
	public AbstractTrackingLock(Lock master) {
		this.master = master;
	}

	@Override
	public void lock() {
		master.lock();
		incCounter();
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		master.lockInterruptibly();
		incCounter();
	}

	@Override
	public boolean tryLock() {
		if (master.tryLock()) {
			incCounter();
			return true;
		}
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		if (master.tryLock(time, unit)) {
			incCounter();
			return true;
		}
		return false;
	}

	@Override
	public void unlock() {
		master.unlock();
		decCounter();
	}

	@Override
	public Condition newCondition() {
		return master.newCondition();
	}

}
