package edu.nyu.cs9053.concurrency.chapter14;

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

/**
 * User: blangel
 * Date: 7/26/14
 * Time: 10:49 AM
 */
public class CannotBeRewritten {

    private final Lock lock = new ReentrantLock();

    private final Condition condition = lock.newCondition();

    private int value;

    public void check(long waitMs) throws InterruptedException {
        if (lock.tryLock(waitMs, TimeUnit.MILLISECONDS)) {
            if (value >= 100) {
                condition.signalAll();
            }
        }
    }

    public void process() {
        lock.lock();
        try {
            value += 1;
        } finally {
            lock.unlock();
        }
    }

    public void print() throws InterruptedException {
        lock.lock();
        try {
            while (value < 100) {
                condition.await();
            }
        } finally {
            lock.unlock();
        }
    }

}
