Skip to content

Dynamic Fork Joins

yogeshnachnani edited this page Apr 11, 2016 · 4 revisions

The code for the following example can be found at SimpleForkJoinWorkflow

There are many cases within a workflow where a number of tasks can be executed concurrently (to speed up execution) and their results collated at a single point. This is a referred to as a fork-join. At times, the number of such tasks to be "forked" is only known at run time. This is called a dynamic fork-join.

In the example below, we perform N number of "forks" before joining their results.

The example solves a simple use case of generating a random permutation of a given string.

@Workflow(version = 1)
public void generateRandomPermutation(String someInputString) {
    /* The value of n is available only at runtime */
    final int n = someInputString.length();
    List<Character> listOfCharacters = new ArrayList<>();
    for (int i = 0; i < n ; i ++) {
        /* fork returns the character at index i */
        listOfCharacters.add(simpleTasker.fork(someInputString, i));
    }
/*
 The following method simply concatenates the given list of characters into a message 
 and saves it to DB.
 Note: Since the fork operations are not inter-dependent on each other, they may be started & completed in any order.
 Thus, the final message may be a different permutation of the given input
*/
    simpleTasker.join(listOfCharacters);
    }
Clone this wiki locally