Saw a very interesting note today from Doug Lea on the concurrency-interest mailing list. Looks like they are extracting a useful internal part of the fork-join framework and making it available in java.util.concurrent as a new Phaser class.
The concurrency-interest archives aren’t open so I’ve taken the liberty of reproducing Doug’s email here:
Date: Mon, 07 Jul 2008 13:19:01 -0400
From: Doug Lea
Subject: [concurrency-interest] Phasers (were: TaskBarriers)
The flexible barrier functionality that was previously restricted to ForkJoinTasks (in class forkjoin.TaskBarrier) is being redone as class Phaser (targeted for j.u.c, not j.u.c.forkjoin), that
can be applied in all kinds of tasks. For a snapshot of API, see http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/jsr166y/Phaser.html
Comments and suggestions are very welcome as always. The API is likely to change a bit as we scope out further uses, and also, hopefully, stumble upon some better method names.
Among its capabilities is allowing the number of parties in a barrier to vary dynamically, which CyclicBarrier doesn’t and can’t support, but people regularly ask for.
The nice new class name is due to Vivek Sarkar. For a preview of some likely follow-ons (mainly, new kinds of FJ tasks that can register in various modes for Phasers, partially in support of analogous X10 functionality), see the paper by Vivek and others:
I use CyclicBarrier all the time and could definitely use some of the new Phaser features. In addition to the existing CyclicBarrier functionality (reusable, barrier actions), Phaser has these features:
- Party count can change dynamically
- Each phase has an incrementing phase number associated
- Termination state (where await actions immediately return)
- Exceptions during waiting do not change barrier state
In CyclicBarrier, the barrier action is implemented by providing a Runnable. In Phaser, barrier actions are implemented by subclassing Phaser and overriding onAdvance(), which gives you easy access to the state of the Phaser. The method itself receives the current phase count and number of currently registered parties. I don’t like the reliance on inheritance here – the CyclicBarrier approach to using an external task is far preferable in my mind.
In any case, it’s awesome to see this work becoming more available. You can, by the way, compile and use the jsr166y library on older JDKs (including the fork-join library), so if you need some Phaser action, you could use it now (with the caveat that it’s a work in progress) without waiting for Java 7 (when you will probably be retired).