The Tasks component simplifies the process of adding data and task parallelism through its Parallel class. This component is especially useful for Java applications because the Java standard library does not have a parallel for loop or parallel invoke.
Currently, Java does not support closure expressions (a block of Java code which is a statement list, an expression or a combination of both). Therefore, PTL implements data and task parallelism using function objects (functors) that wrap the code that will be executed in parallel in a "Call" method that acts as a function call operator (as seen in the code examples below).
The Parallel class provides a parallel for loop in Java. You write the loop logic for a Java Parallel.For loop similar to how you would write a sequential loop, and PTL handles the low-level work for you.
ArrayList<Item> collection = ... void Process(Item item) { // ... } // Sequential version for (int i = 0; i < collection.size(); i++) { Process(collection.get(i)); } // Parallel equivalent Parallel.For(0, collection.size(), new ProcessItem(collection)); private class ProcessItem implements IAction1Arg<Item> { ProcessItem(ArrayList<Item> list) { this.collection = collection; } @Override public void Call(Integer i) { Process(collection.get(i)); } ArrayList<Item> collection; }
The Parallel class also provides a parallel invoke method in Java, which allows you to run any number of arbitrary statements concurrently.
Parallel.Invoke(new DoSomeWork(), new DoSomeOtherWork()); private class DoSomeWork implements IAction0Arg { @Override public void Call() { // ... } } private class DoSomeOtherWork implements IAction0Arg { @Override public void Call() { // ... } }