2

I'm implementing a SimpleSemaphore using ReentrantLock in Java.

Now, I would like to add it a fairness flag, to make it behave as a fair\unfair semaphore, as defined in its constructor.

Here's my SimpleSemaphore code, I'd be happy for some tips on how to begin to implement fairness. Thank you.

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

/**
 * @class SimpleSemaphore
 *
 * @brief This class provides a simple counting semaphore
 *        implementation using Java a ReentrantLock and a
 *        ConditionObject.  It must implement both "Fair" and
 *        "NonFair" semaphore semantics, just liked Java Semaphores. 
 */
public class SimpleSemaphore {
    private int mPermits;
    private ReentrantLock lock = new ReentrantLock();
    private Condition isZero = lock.newCondition();

    /**
     * Constructor initialize the data members.  
     */
    public SimpleSemaphore (int permits,
                            boolean fair)
    { 
        mPermits = permits;
    }

    /**
     * Acquire one permit from the semaphore in a manner that can
     * be interrupted.
     */
    public void acquire() throws InterruptedException {
        lock.lock();
        while (mPermits == 0)
            isZero.await();
        mPermits--;
        lock.unlock();
    }

    /**
     * Acquire one permit from the semaphore in a manner that
     * cannot be interrupted.
     */
    public void acquireUninterruptibly() {
        lock.lock();
        while (mPermits == 0)
            try {
                isZero.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        mPermits--;
        lock.unlock();
    }

    /**
     * Return one permit to the semaphore.
     */
    void release() {
        lock.lock();
        try {
            mPermits++;
            isZero.signal();
        } finally {
            lock.unlock();
        }
    }
}
DanielY
  • 1,141
  • 30
  • 58

1 Answers1

3

try this

...
    private ReentrantLock lock;
    private Condition isZero;

    public SimpleSemaphore (int permits, boolean fair) { 
        mPermits = permits;
        lock = new ReentrantLock(fair);
        isZero = lock.newCondition();
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Thank you very much! Is my acquire and acquireUninterruptibly methods ok? they are pretty much the same so I wasn't sure if I'm doing good here... – DanielY Apr 30 '14 at 05:35
  • I would use Lock.awaitUninterruptibly() for acquireUninterruptibly() – Evgeniy Dorofeev Apr 30 '14 at 05:38
  • 3
    Evgeniy, nice answer. However, you may not have known that the question is a homework assignment. By posting your answer, you're inadvertently helping students cheat. – tpdi Jun 03 '14 at 08:25