Saturday 11 February 2012

ExecutorService

To easily run many Threads in java ExecutorService can be used. It is an abstraction for creating a pool of threads for running tasks. Tasks can return results in Future object. We can create Thread pools using methods of class Executors. There are plenty of options: amount of Threads to use, rise of ones,...
More details can be found on: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

An example of using these construction is here:
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {

 final int size = 20000000;

 private long[] arr = new long[size];

 class Task implements Callable {

  private int index, range;

  public Task(int index, int range) {
   this.index = index;
   this.range = range;
  }

  public Boolean call() throws Exception {
   boolean ret = false;

   for (int i = index; i < index + range; i++) {

   }

   return ret;
  }

 }

 public ExecutorServiceExample() {
  Random random = new Random(new Date().getTime());
  for (int i = 0; i < size; i++) {
   arr[i] = random.nextLong();
  }
 }

 public static void main(String[] args) {

  ExecutorServiceExample ese = new ExecutorServiceExample();
  ese.findSeq(123456789012345678l);
  ese.findConcur(123456789012345678l);

 }

 private boolean check(int i, long val) {
  if (arr[i] * val * val == val * val * val) {
   System.out.println("Found:" + i);
   return true;
  }
  return false;
 }

 private void findConcur(long val) {
  int range = 100;
  long start = new Date().getTime();
  ExecutorService service = Executors.newFixedThreadPool(100);

  for (int i = 0; i < size / range; i++) {
   service.submit(new Task(i * range, range));
  }
  service.shutdown();
  System.out.println("Seq in " + (new Date().getTime() - start));
 }

 private void findSeq(long val) {
  long start = new Date().getTime();
  for (int i = 0; i < size; i++) {
   check(i, val);
  }
  System.out.println("Seq in " + (new Date().getTime() - start));
 }
}

To run this example you will probably need to add parameter to increase heap size (f.e. -Xmx1300m)

No comments: