package edu.nyu.cs9053.concurrency.semaphore;

import java.util.concurrent.Semaphore;

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

    private final Semaphore binarySemaphore;

    private long sequence;

    public UniqueNumberGenerator() {
        this(new Semaphore(1));
    }

    public UniqueNumberGenerator(Semaphore binarySemaphore) {
        this.binarySemaphore = binarySemaphore;
        this.sequence = 0L;
    }

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

}
