An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

The ExecutorService class provides an easy way to run paralell task in javascript by wrapping a a work-stealing thread pool using the number of availableProcessors available processors as its target parallelism level.

1 Using ExecutorService

You can call a javscript function that receives an argument in parallel by calling:
executor.invokeAndGet(jsfunction, argumentlist)
where jsfunction is the name of the javascript function and argumentlist is an array of arguments of the type the function expects.

This implementation makes several assumptions about the tasks passed

  • they should not depend on any external function or value
  • they should not be closures
  • they should accept one argument only, and output only one result
  • they should have no side-effects

Copy

Determine if numbers of a list are primes

<script>
    function isPrime(n) {
    
        if (n === 1) {
            return false;
        } else if (n === 2) {
            return true;
        } else {
            for (var x = 2; x < n; x++) {
                if (n % x === 0) {
                    return false;
                }
            }
            return true;
        }
    }
    
    let executor = new Ax.util.ExecutorService();
    
    // =========================================================
    // Create a list of number from 50000000 to 50000000+1000
    // =========================================================
    var list = new Array(1000)
        .join().split(',')
        .map(function(item, index) {
            return ++index + 50000000;
        });
    console.log(list);
    
    // =========================================================
    // Run task in parallel
    // =========================================================
    console.time("parallel");
    var r_parallel = executor.invokeAndGet(isPrime, list);
    console.timeEnd("parallel");
    console.log(r_parallel);
    
    // =========================================================
    // Run task sequential
    // =========================================================
    console.time("sequential");
    var r_sequential = list.map(isPrime);
    console.timeEnd("sequential");
    console.log(r_sequential);
</script>