Blog
Exploring Javas Fork Join Framework
Sep 17, 2012
We've been taking a look at concurrency recently, which leaves an excellent opportunity to study Java's new(ish) Fork/Join framework. The idea is, you have a task, and if it can benifit from splitting into a bunch of threads it forks out, and later joins them together when the work is done.
Traditionally, to make a thread we(I) do something like this main():
Thread myThread = new Thread(new Runnable(){
public void run(){
System.out.println("Hello from thread 1.");
}
});
Then, to start the thread:
myThread.start();
Then, sometime later we want to make sure the thread has finished before moving on, so we say:
myThread.join();
And we go about our business as usual. Now, let's take a look at how Fork/Join does it:
My laptop has 2 processors, and so all I needed to do to see this in action was:
- Download java jdk-7, since I had jdk-6 which doesn't support Fork/Join.
- Find the ForkBlur.java demo program on javas site.
- Find a picture of a Sneech.
- Change line 104 in the code.
- javac and java using my new jdk-7
The result is a blurred Sneech cover, AWESOME!

So what's going on here? Let's take a look at line 89:
protected void compute() {
if (mLength < sThreshold) {
computeDirectly();
return;
}
int split = mLength / 2;
invokeAll(new ForkBlur(mSource, mStart, split, mDestination),
new ForkBlur(mSource, mStart + split, mLength - split, mDestination));
}
This is performing a single (unthreaded) computation if
mLength < sThreshold
and if not, it splits into 2 threads (one processing the first half of the image, the other processing the second half.