package edu.nyu.cs9053.concurrency.mutex;

import java.util.concurrent.Semaphore;

/**
 * User: blangel
 * Date: 11/9/14
 * Time: 2:55 PM
 */
public class UniqueNumberGenerator {

    private final Semaphore mutex;

    private long sequence;

    public UniqueNumberGenerator() {
        this.mutex = new Semaphore(1);
        this.sequence = 0L;
    }

    public long next() {
        try {
            mutex.acquire();
            return sequence++;
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(ie);
        } finally {
            mutex.release();
        }
    }

}
