package edu.nyu.cs9053.concurrency.livelock;

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

/**
 * User: blangel
 * Date: 11/9/14
 * Time: 11:57 AM
 */
public class Walker {

    private final AbstractDirection first;

    private final AbstractDirection second;

    public Walker(AbstractDirection first, AbstractDirection second) {
        this.first = first;
        this.second = second;
    }

    public boolean attemptPass() throws InterruptedException {
        while (true) {
            System.out.printf("Trying %s...%n", first.toString());
            if (first.tryLock(100L, TimeUnit.MILLISECONDS)) {
                System.out.printf("Trying %s...%n", second.toString());
                if (second.tryLock(100L, TimeUnit.MILLISECONDS)) {
                    return true;
                }
            }
        }
    }

}
