Skip to main content
summaryrefslogtreecommitdiffstats
blob: 24ef93029c52b8881461d88d95ec899c61c92f40 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*******************************************************************************
 * Copyright (c) 2012 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.core.threading;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.eclipse.osee.framework.core.exception.OseeExceptions;
import org.eclipse.osee.framework.jdk.core.type.OseeCoreException;

/**
 * @author John R. Misinco
 */
public class ThreadedWorkerExecutor<T> {

   private final int numberOfWorkers;
   private final ThreadedWorkerFactory<T> factory;

   public ThreadedWorkerExecutor(ThreadedWorkerFactory<T> factory, boolean ioBound) {
      this(factory,
         ioBound ? Runtime.getRuntime().availableProcessors() * 2 : Runtime.getRuntime().availableProcessors());
   }

   public ThreadedWorkerExecutor(ThreadedWorkerFactory<T> factory, int numberOfWorkers) {
      this.factory = factory;
      this.numberOfWorkers = numberOfWorkers;
   }

   public List<T> executeWorkersBlocking() throws OseeCoreException {
      ExecutorService executor = Executors.newFixedThreadPool(numberOfWorkers);
      List<T> toReturn = new LinkedList<T>();
      Collection<Callable<T>> workers = createWorkers();

      try {
         for (Future<T> future : executor.invokeAll(workers)) {
            toReturn.add(future.get());
         }
      } catch (Exception ex) {
         OseeExceptions.wrapAndThrow(ex);
      } finally {
         executor.shutdown();
      }
      return toReturn;
   }

   private Collection<Callable<T>> createWorkers() {
      int partitionSize = factory.getWorkSize() / numberOfWorkers;
      int remainder = factory.getWorkSize() % numberOfWorkers;
      int startIndex = 0;
      int endIndex = 0;
      Collection<Callable<T>> workers = new LinkedList<Callable<T>>();
      for (int i = 0; i < numberOfWorkers; i++) {
         startIndex = endIndex;
         endIndex = startIndex + partitionSize;
         if (i == 0) {
            endIndex += remainder;
         }
         workers.add(factory.createWorker(startIndex, endIndex));
      }
      return workers;
   }

}

Back to the top