I need to process elements in some Collection instance concurrently. In other words instead of iterating a Collection instance
for (Someclass elem : coll){
     process(elem);
}
I’d like to process those elements concurrently. Say, something like ConcurrentCollectionExecutor(coll, new Callable{…}, numberOfThreads). Also, a number of simultaneous threads should be fixed.
Any flexible pattern already exists?
Make the process method a run() method in a class called MyRunnable that implements Runnable and whose constructor takes elem as input and stores it as an instance variable. Then use:
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
for (Someclass elem : coll){
   Runnable worker = new MyRunnable(elem);
   executor.execute(worker);
}
                        A good solution would be:
Runnables giving them the ArrayBlockingQueue as parameterrun method: while there elements in the queue, poll them and process themRunnables to the ExecutorService
The code:
BlockingQueue<Someclass> toProcess = 
    new ArrayBlockingQueue<Someclass>(coll.size(), false, coll);
ExecutorService es = Executors.newFixedThreadPool(numberOfThreads);
for(int count = 0 ; count < numberOfThreads ; ++c) {
    es.submit(new MyRunnable(toProcess));
}
private static class MyRunnable() implements Runnable {
    private final BlockingQueue<Someclass> toProcess;
    public MyRunnable(BlockingQueue<Someclass> toProcess) {
        this.toProcess = toProcess;
    }
    @Override
    public void run() {
        Someclass element = null;
        while((element = toProcess.poll()) != null) {
            process(element);
        }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With