01 /*
02 * Java Genetic Algorithm Library (jenetics-3.5.0).
03 * Copyright (c) 2007-2016 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
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 :
60 new ArrayList<>(runnables),
61 0,
62 runnables.size(),
63 null
64 );
65 }
66
67 @Override
68 protected void compute() {
69 final int threshold = _threshold != null ? _threshold : threshold();
70
71 if (_high - _low < threshold) {
72 for (int i = _low; i < _high; ++i) {
73 _runnables.get(i).run();
74 }
75 } else {
76 final int mid = (_low + _high) >>> 1;
77 invokeAll(
78 new RunnablesAction(_runnables, _low, mid, threshold),
79 new RunnablesAction(_runnables, mid, _high, threshold)
80 );
81 }
82 }
83
84 private int threshold() {
85 return max(_runnables.size()/(Concurrency.CORES*2), DEFAULT_THRESHOLD);
86 }
87
88 }
|