I write this blog to share the solutions and problems I have found with fellow software engineers. I also do it to remind myself of what I've already figured out ;)

Sunday, June 17, 2007

Producer Consumer Example using Java.Util.Concurrent and a CompletionService

Blogger screws up indentations, so sorry the source looks ugly. The code does work however.

Main Class

package test;

import java.util.concurrent.*;

public class Main {

public static CompletionService cs;
private final static int poolSize = 4;
public static volatile int counter = 1;
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(poolSize);
cs = new ExecutorCompletionService(pool);
(new Producer()).run();
(new Consumer()).run();
}

}

Producer Class
package test;

public class Producer extends Thread {

@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Submitting Task " + i);
Main.cs.submit(new Task1(i));
}
}

}

Consumer Class

package test;

import java.util.concurrent.ExecutionException;

public class Consumer extends Thread {

@Override
public void run() {
int i = 0;
while(true) {
try {
Integer j = Main.cs.take().get();
i++;
System.out.println("Took out task " + i + " with result:" + j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

Task Class

package test;

import java.util.concurrent.Callable;

public class Task1 implements Callable {

int id;

Task1 (int i){
id = i;
}

public Object call() throws Exception {
Thread.sleep(1000*Main.counter);
Main.counter++;
System.out.println("In Task1 and just iterated counter to:" + Main.counter);
return Main.counter;
}

}


No comments: