Google

Jul 2, 2014

Java Executor service examples to run concurrently and sequentially with strategy design pattern - part 1

This is a three part series on Java executor framework for running multi-threaded applications.

Part 1: Running concurrent threads
Part 2: Running sequential threads
Part 3: Creating a strategy class using the strategy design pattern to be able switch between running concurrently and sequentially.


package com.writtentest13;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 
 * Tasks are executed concurrently in a thread pool
 */
public class ThreadExecutorMainCon  {

 private ExecutorService concurrentThreadExecutor;

 public static void main(String[] args) {
  ThreadExecutorMainCon main = new ThreadExecutorMainCon();

  // concurrent executor
  main.concurrentThreadExecutor = Executors.newCachedThreadPool();// or
                  // newFixedThreadPool(3)
  List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();

  // create dummy tasks
  for (int i = 1; i <= 5; i++) {
   tasks.add(main.createTask(i));
  }

  // submit the tasks to the concurrentThreadExecutor
  try {
      main.concurrentThreadExecutor.invokeAll(tasks);

  } catch (InterruptedException e) {
       e.printStackTrace();
  }

  System.out.println("Completed .........");

 }

 private Callable<Boolean> createTask(final int i) {

  Callable<Boolean> task = new Callable<Boolean>() {

   @Override
   public Boolean call() throws Exception {
      System.out.println("Performing task " + i + " on thread - " + Thread.currentThread().getName());
      return true;
   }

  };

  return task;

 }
}


The output will be

Performing task 1 on thread - pool-1-thread-1
Performing task 5 on thread - pool-1-thread-4
Performing task 4 on thread - pool-1-thread-1
Performing task 3 on thread - pool-1-thread-3
Performing task 2 on thread - pool-1-thread-2
Completed .........


You can see more than 1 thread process 5 tasks concurrently. Try changing the Executors.newCachedThreadPool () to Executors.newFixedThreadPool(3) for max 3 threads to execute concurrently. In the next post, we will look at running the task sequentially in the current thread, which involves more coding.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home