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: Stefan Profanter - initial API and implementation, Year: 2012
00007  ******************************************************************************/
00008 package edu.tum.cs.ias.knowrob.utils;
00009 
00010 import java.util.List;
00011 import java.util.concurrent.Callable;
00012 import java.util.concurrent.ExecutionException;
00013 import java.util.concurrent.ExecutorService;
00014 import java.util.concurrent.Executors;
00015 import java.util.concurrent.Future;
00016 
00023 public class ThreadPool {
00024 
00033         public static void executeInPool(List<Callable<Void>> threads) {
00034                 executeInPool(threads, -1);
00035         }
00036         public static void executeInPool(List<Callable<Void>> threads, int numParallel) {
00037                 ExecutorService pool;
00038                 int threadNum = numParallel <= 0 ? Runtime.getRuntime().availableProcessors() * 2 : numParallel;
00039                 pool = Executors.newFixedThreadPool(threadNum);
00040 
00041                 try {
00042                         List<Future<Void>> futures = pool.invokeAll(threads);
00043                         for (Future<Void> f : futures) {
00044                                 try {
00045                                         f.get(); // If called thread threw an exception, get will throw an
00046                                                                 // ExecutionException
00047                                 } catch (ExecutionException ex) {
00048                                         ex.getCause().printStackTrace(); // Print exceptions from called threads if
00049                                                                                                                 // there were any
00050                                 }
00051                         }
00052                 } catch (InterruptedException e) {
00053                         e.printStackTrace();
00054                 }
00055                 threads.clear();
00056         }
00057 }


knowrob_common
Author(s): Moritz Tenorth
autogenerated on Sat Dec 28 2013 17:09:28