ThreadPool.java
Go to the documentation of this file.
00001 /*******************************************************************************
00002  * Copyright (c) 2012 Stefan Profanter. All rights reserved. This program and the accompanying
00003  * materials are made available under the terms of the GNU Public License v3.0 which accompanies
00004  * this distribution, and is available at http://www.gnu.org/licenses/gpl.html
00005  * 
00006  * Contributors: 
00007  *                              Stefan Profanter - initial API and implementation, Year: 2012
00008  *                              Andrei Stoica - minor refactor during Google Summer of Code 2014
00009  ******************************************************************************/
00010 package edu.tum.cs.ias.knowrob.utils;
00011 
00012 import java.util.List;
00013 import java.util.concurrent.Callable;
00014 import java.util.concurrent.ExecutionException;
00015 import java.util.concurrent.ExecutorService;
00016 import java.util.concurrent.Executors;
00017 import java.util.concurrent.Future;
00018 
00025 public class ThreadPool {
00026 
00035         public static void executeInPool(List<Callable<Void>> threads) {
00036                 executeInPool(threads, -1);
00037         }
00038         
00039         public static void executeInPool(List<Callable<Void>> threads, int numParallel) {
00040                 ExecutorService pool;
00041                 int threadNum = numParallel <= 0 ? Runtime.getRuntime().availableProcessors() * 2 : numParallel;
00042                 pool = Executors.newFixedThreadPool(threadNum);
00043 
00044                 try {
00045                         List<Future<Void>> futures = pool.invokeAll(threads);
00046                         for (Future<Void> f : futures) {
00047                                 try {
00048                                         f.get(); // If called thread threw an exception, get will throw an
00049                                                                 // ExecutionException
00050                                 } catch (ExecutionException ex) {
00051                                         ex.getCause().printStackTrace(); // Print exceptions from called threads if
00052                                                                                                                 // there were any
00053                                 }
00054                         }
00055                 } catch (InterruptedException e) {
00056                         e.printStackTrace();
00057                 }
00058                 threads.clear();
00059                 pool.shutdown();
00060         }
00061 }


knowrob_common
Author(s): Moritz Tenorth
autogenerated on Mon Oct 6 2014 01:29:31