01 /*
02 * Java Genetic Algorithm Library (jenetics-2.0.2).
03 * Copyright (c) 2007-2014 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19 */
20 package org.jenetics.internal.util;
21
22 import static java.lang.Math.max;
23
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.RandomAccess;
27 import java.util.concurrent.RecursiveAction;
28
29 /**
30 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
31 * @version 2.0 — <em>$Date: 2014-04-16 $</em>
32 * @since 2.0
33 */
34 final class RunnablesAction extends RecursiveAction {
35 private static final long serialVersionUID = 1;
36
37 private static final int DEFAULT_THRESHOLD = 7;
38
39 private final List<? extends Runnable> _runnables;
40 private final int _high;
41 private final int _low;
42 private final Integer _threshold;
43
44 private RunnablesAction(
45 final List<? extends Runnable> runnables,
46 final int low,
47 final int high,
48 final Integer threshold
49 ) {
50 _runnables = runnables;
51 _low = low;
52 _high = high;
53 _threshold = threshold;
54 }
55
56 public RunnablesAction(final List<? extends Runnable> runnables) {
57 this(
58 runnables instanceof RandomAccess ?
59 runnables : new ArrayList<>(runnables),
60 0, runnables.size(), null
61 );
62 }
63
64 @Override
65 protected void compute() {
66 final int threshold = _threshold != null ? _threshold : threshold();
67
68 if (_high - _low < threshold) {
69 for (int i = _low; i < _high; ++i) {
70 _runnables.get(i).run();
71 }
72 } else {
73 final int mid = (_low + _high) >>> 1;
74 invokeAll(
75 new RunnablesAction(_runnables, _low, mid, threshold),
76 new RunnablesAction(_runnables, mid, _high, threshold)
77 );
78 }
79 }
80
81 private int threshold() {
82 return max(_runnables.size()/(Concurrency.CORES*2), DEFAULT_THRESHOLD);
83 }
84
85 }
|