I am wondering how I could design methods that could either be run concurrently or single threaded. For example I have a method like this:
/**
* Produces the norm of the two vector {@code v1}.
*
* @param v1
* The first vector.
*
* @param v2
* The second vector
*
* @throws MathException
* Of type {@code DIMENSION_MISMATCH} if
* {@code v1.getDimension()} is != {@code v2.getDimension()}.
*/
public static Function<Vector, Double> norm = (v) -> {
return Math.sqrt(
IntStream.range(0, v.getDimension()).mapToDouble(i -> Math.pow(v.getEntry(i), 2)).sum());
};
And if I want to make the embedded stream parallel then I could create the same method over again and add parallel()
to the stream but that adds a lot of boilerplate. Is there a parallel(boolean)
switch that can be used?
There is no switch like this in the API itself but you can add it yourself quite easily:
This code simply calls
parallel()
or not depending on the boolean parameter.Just wanted to post an example of what I think the API should look like in general to see what you think (I'm hoping Apache Commons Math will adopt this for 4.0, but the module will be available here meanwhile firefly-math-linear-real):
Thoughts?
Ole
Create two functions
one named norm (implementation as provided in question), another named parallelNorm. You could reuse code between those functions.
Let encosing class controll parallelism
Your function norm resides in some class. I would
Use Decorator pattern to add parallelism
like in example above, I would use non-static function. I would make one class named Norm (with implementation of norm function like above). Then I would make class ParallelNorm extends Norm that would @Override norm function with parallel implementation