001/**
002 * Copyright 2010-2014 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.common.util.base;
017
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.collect.Lists.newArrayList;
020import static java.util.Collections.emptyList;
021import static java.util.concurrent.Executors.newFixedThreadPool;
022import static org.kuali.common.util.base.Exceptions.illegalState;
023
024import java.util.List;
025import java.util.concurrent.Callable;
026import java.util.concurrent.ExecutionException;
027import java.util.concurrent.ExecutorService;
028import java.util.concurrent.Future;
029
030public class Callables {
031
032        public static <T> List<T> submitCallables(List<? extends Callable<T>> callables) {
033                checkNotNull(callables);
034                if (callables.isEmpty()) {
035                        return emptyList();
036                }
037                ExecutorService pool = newFixedThreadPool(callables.size());
038                List<Future<T>> futures = newArrayList();
039                for (Callable<T> callable : callables) {
040                        futures.add(pool.submit(callable));
041                }
042                List<T> elements = newArrayList();
043                for (Future<T> future : futures) {
044                        elements.add(get(future));
045                }
046                return elements;
047        }
048
049        protected static <T> T get(Future<T> future) {
050                try {
051                        return future.get();
052                } catch (InterruptedException e) {
053                        throw illegalState(e);
054                } catch (ExecutionException e) {
055                        throw illegalState(e);
056                }
057        }
058}