Search code examples
javaconcurrencyphaser

How do I find out when the last party fires Phaser.arrive()?


Given:

Executor executor = ...;
Phaser phaser = new Phaser(n);
for (int i=0; i<n; ++i)
{
  Runnable task = new Runnable()
  {
    public void run()
    {
      phaser.arriveAndDeregister();
      if (lastTask)
        doSomething(this);
    }
  }

  // run tasks using a thread-pool (order is not guaranteed)
  executor.submit(task);
}

I'd like to find out if I'm the last task in order to fire doSomething() that depends upon the task's internal state. I found Phaser.onAdvance(int, int) but it's not clear how to use it in this case.


Solution

  • I can't think of a very elegant way of solving this but the use of ThreadLocal and the onAdvance can help.

        final ThreadLocal<Boolean> isLast = new ThreadLocal<Boolean>() {
            public Boolean initialValue() {
                return false;
            }
        };
        final Phaser p = new Phaser(9) {
            public boolean onAdvance(int phase, int registeredParties) {
                isLast.set(true);
                return true;
            }
        };
    

    Then

      public void run()
        {
          phaser.arriveAndDeregister();
          if (isLast.get())
            doSomething(this);
        }