[concurrency-interest] Enforcing ordered execution of critical sections?

Doug Lea dl at cs.oswego.edu
Mon Dec 22 09:36:16 EST 2014


On 12/21/2014 07:25 PM, Joe Bowbeer wrote:
> Below is the most concise implementation I can imagine, using a single
> Semaphore, which is legal AFAICT according to the javadoc, but which deadlocks
> in my tests.

This makes a too-strong assumption about Semaphore.acquire(n), that
waiters do not independently try to accumulate permits.
I suppose that we don't explicitly rule this out, but do state...

"This class also provides convenience methods to acquire and release multiple 
permits at a time. Beware of the increased risk of indefinite postponement when 
these methods are used without fairness set true. "

The acquire(n) spec should probably be clarified that it promises
no more than the equivalent of
   for (int i = 0; i < n; ++i) acquire();

-Doug


>
> class OrderedExecutor<T> {
>
>    private final Semaphore semaphore = new Semaphore(1);
>
>    @Override
>    public T execCallableInOrder(int order, Callable<T> callable)
>        throws InterruptedException, Exception {
>      assert order >= 0;
>      int acquires = order + 1;
>      semaphore.acquire(acquires);
>      try {
>        return callable.call();
>      } finally {
>        semaphore.release(acquires + 1);
>      }
>    }
> }






More information about the Concurrency-interest mailing list