//java architect /
Fork/Join Framework for
Client Java Applications
Java SE 7’s fork/join framework makes a great match for CPU-intensive client-side applications.
JOSH MARINACCI
JAVA IN ACTION
CPUs aren’t getting faster. Nearly ten years ago, we hit
3 GHz and I have yet to own a
4 GHz machine, much less the
43 GHz Moore’s Law promised
me. CPUs can do far more than
they used to, but they do it by
getting wider instead of faster—
more CPUs with more cores with
more threads.
While this is great for the end
user, it introduces new challenges
for application developers. I can
buy a 12-core desktop from Apple,
and even my small laptop has 2
cores now. The world is becoming
parallel, so we need new ways to
code for parallel machines.
Java has always had good sup-
port for concurrent programming
thanks to java.lang. Thread. The
Thread class has existed since the
first release of J2SE 5.0 introduced
the ExecutorService to ease the
management of groups of threads.
Unfortunately, threads mainly
help with I/O-bound tasks. That’s
fine for server-side jobs, such as
hosting Web apps, but modern
desktop apps need help with CPU-
bound tasks as well.
if you don’t know
the scope of the
work beforehand.
■ ■ Fork/join provides
work-stealing
behavior that can
better balance the
workload across
multiple processors, and with less
lock contention.
Traditional algorithms can max out
at about eight processors before the
overhead of lock
contention outweighs the speed of
using more cores.
Fork/join can scale
to over 100 cores.
■ ■ Fork/join is future-proof and portable. The code
you write with it doesn’t
assume anything about the
underlying hardware. It’s
designed to run your code as
efficiently as possible across
any hardware—both today’s
Every class that
uses the fork/join
framework works
with pretty much
this algorithm: If the
amount of work is
below a threshold,
then do the work;
other wise, split
the work in half and
recurse, waiting
for each half to
complete.
dual-core laptops
and single-core
phones, as well as the
100-core desktop of
the future.
Something Simple
To see how the fork/
join framework works,
let’s try something
simple. Every class
that uses the fork/join
framework works with
pretty much this algorithm (see Listing 1):
If the amount of work
is below a threshold,
then do the work;
otherwise, split the
work in half and
recurse, waiting for
each half to complete.
This is the textbook divide-and-conquer method.
To demonstrate how this works
in practice, I’ve created a simple
example that calculates the minimum number from a very large
array of doubles (see Listing 2).
ABOUT US
blog
PHOTOGRAPH BY
CHRIS PIETSCH/GETTY IMAGES
Fork/Join Framework
The fork/join framework provides
three benefits over the Executor
interface.
■ ■ Fork/join is a natural fit for a
recursive algorithm, especially