Parallel execution

Both execute methods of the Request are blocking, which means that a thread is required for each robot execution. The examples we have looked at until now have all executed the robot directly on the main thread, which is typically not preferable as you can only execute a single robot at a time in a sequential manner.

Let's look at an example that will execute two tutorial robots in parallel. This example uses the java.util.concurrent library for multithreading.


import com.kapowtech.robosuite.api.java.repository.construct.*;
import com.kapowtech.robosuite.api.java.rql.*;
import com.kapowtech.robosuite.api.java.rql.construct.*;
import com.kapowtech.robosuite.api.java.rql.engine.hotstandby.*;

import java.util.concurrent.*;

public class ParallelExecution {

    public static void main(String[] args) throws Exception {

        RoboServer server = new RoboServer("localhost", 50000);
        Cluster cluster = new Cluster("MyCluster", new RoboServer[] {server}, false);
        Request.registerCluster(cluster);

        int numRobots = 4;
        int numThreads = 2;
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(numThreads, numThreads, 10, TimeUnit.SECONDS, new LinkedBlockingQueue());
        for (int i = 0; i < numRobots; i++) {
            Request request = new Request("Library:/Tutorials/NewsMagazine.robot");
            request.setRobotLibrary(new DefaultRobotLibrary());
            threadPool.execute(new RobotRunnable(request));
        }
        threadPool.shutdown();
        threadPool.awaitTermination(60, TimeUnit.SECONDS);
    }

    // -----------------------------------------------------------------
    // Inner classes
    // -----------------------------------------------------------------
    static class RobotRunnable implements Runnable {

        Request _request;

        RobotRunnable(Request request) {
            _request = request;
        }

        public void run() {

            try {
                RQLResult result = _request.execute("MyCluster");
                System.out.println(result);
            }
            catch (RQLException e) {
                e.printStackTrace();
            }
        }
    }
}
                    

Multithreading Example


The above example creates a ThreadPoolExecutor with two threads, we then creates four RobotRunnables and execute them on the thread pool. Since the thread pool has two threads, two robots will start to execute immediately, the remaining two will be parked in the LinkedBlockingQueue and executed in order as the two first robot finish their execution and the thread pool threads become available.

Please note that the Request is mutable, to avoid raise conditions the Request is cloned inside the execute method. Because Request is mutable you should never modify the same Request on separate threads.