All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fr.profi.mzdb.util.threading.Executor Maven / Gradle / Ivy

There is a newer version: 0.0.27
Show newest version
/**
 * Class launching several threads with runnable or callables
 * size of runnable array can be greater than the number of cores
 */
package fr.profi.mzdb.util.threading;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author marco
 * 
 */
public class Executor {

	private ExecutorService pool;
	private Callable[] callables = null;
	private Runnable[] runnables = null;
	private List> futures = new ArrayList>();

	public Executor(Callable[] r, int core) {
		pool = Executors.newFixedThreadPool(core);
		callables = r;
	}

	public Executor(Runnable[] r, int core) {
		pool = Executors.newFixedThreadPool(core);
		runnables = r;
	}

	public List getResults() throws InterruptedException, ExecutionException {
		for (Callable t : callables) {
			Future f = pool.submit(t);
			futures.add(f);
		}
		pool.shutdown();
		List r = new ArrayList(futures.size());
		for (Future future : futures)
			r.add(future.get());
		return r;

	}

	public void start() throws InterruptedException {
		for (Runnable t : runnables)
			pool.execute(t);
		pool.shutdown();
		while (!pool.awaitTermination(1, TimeUnit.SECONDS)) {
			System.out.println("Waiting for tasks to shutdown");
		}
	}

}