< prev index next >

src/java.base/share/classes/java/util/stream/AbstractTask.java

Print this page
rev 47749 : 8190974: Parallel stream execution within a custom ForkJoinPool should obey the parallelism
Reviewed-by: martin, tvaleev
   1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util.stream;
  26 
  27 import java.util.Spliterator;
  28 import java.util.concurrent.CountedCompleter;
  29 import java.util.concurrent.ForkJoinPool;

  30 
  31 /**
  32  * Abstract base class for most fork-join tasks used to implement stream ops.
  33  * Manages splitting logic, tracking of child tasks, and intermediate results.
  34  * Each task is associated with a {@link Spliterator} that describes the portion
  35  * of the input associated with the subtree rooted at this task.
  36  * Tasks may be leaf nodes (which will traverse the elements of
  37  * the {@code Spliterator}) or internal nodes (which split the
  38  * {@code Spliterator} into multiple child tasks).
  39  *
  40  * @implNote
  41  * <p>This class is based on {@link CountedCompleter}, a form of fork-join task
  42  * where each task has a semaphore-like count of uncompleted children, and the
  43  * task is implicitly completed and notified when its last child completes.
  44  * Internal node tasks will likely override the {@code onCompletion} method from
  45  * {@code CountedCompleter} to merge the results from child tasks into the
  46  * current task's result.
  47  *
  48  * <p>Splitting and setting up the child task links is done by {@code compute()}
  49  * for internal nodes.  At {@code compute()} time for leaf nodes, it is


  71  *             setLocalResult(result);
  72  *         }
  73  *     }
  74  * }</pre>
  75  *
  76  * <p>Serialization is not supported as there is no intention to serialize
  77  * tasks managed by stream ops.
  78  *
  79  * @param <P_IN> Type of elements input to the pipeline
  80  * @param <P_OUT> Type of elements output from the pipeline
  81  * @param <R> Type of intermediate result, which may be different from operation
  82  *        result type
  83  * @param <K> Type of parent, child and sibling tasks
  84  * @since 1.8
  85  */
  86 @SuppressWarnings("serial")
  87 abstract class AbstractTask<P_IN, P_OUT, R,
  88                             K extends AbstractTask<P_IN, P_OUT, R, K>>
  89         extends CountedCompleter<R> {
  90 
  91     /**
  92      * Default target factor of leaf tasks for parallel decomposition.
  93      * To allow load balancing, we over-partition, currently to approximately
  94      * four tasks per processor, which enables others to help out
  95      * if leaf tasks are uneven or some processors are otherwise busy.
  96      */
  97     static final int LEAF_TARGET = ForkJoinPool.getCommonPoolParallelism() << 2;
  98 
  99     /** The pipeline helper, common to all tasks in a computation */
 100     protected final PipelineHelper<P_OUT> helper;
 101 
 102     /**
 103      * The spliterator for the portion of the input associated with the subtree
 104      * rooted at this task
 105      */
 106     protected Spliterator<P_IN> spliterator;
 107 
 108     /** Target leaf size, common to all tasks in a computation */
 109     protected long targetSize; // may be lazily initialized
 110 
 111     /**
 112      * The left child.
 113      * null if no children
 114      * if non-null rightChild is non-null
 115      */
 116     protected K leftChild;
 117 


 140         this.spliterator = spliterator;
 141         this.targetSize = 0L;
 142     }
 143 
 144     /**
 145      * Constructor for non-root nodes.
 146      *
 147      * @param parent this node's parent task
 148      * @param spliterator {@code Spliterator} describing the subtree rooted at
 149      *        this node, obtained by splitting the parent {@code Spliterator}
 150      */
 151     protected AbstractTask(K parent,
 152                            Spliterator<P_IN> spliterator) {
 153         super(parent);
 154         this.spliterator = spliterator;
 155         this.helper = parent.helper;
 156         this.targetSize = parent.targetSize;
 157     }
 158 
 159     /**
















 160      * Constructs a new node of type T whose parent is the receiver; must call
 161      * the AbstractTask(T, Spliterator) constructor with the receiver and the
 162      * provided Spliterator.
 163      *
 164      * @param spliterator {@code Spliterator} describing the subtree rooted at
 165      *        this node, obtained by splitting the parent {@code Spliterator}
 166      * @return newly constructed child node
 167      */
 168     protected abstract K makeChild(Spliterator<P_IN> spliterator);
 169 
 170     /**
 171      * Computes the result associated with a leaf node.  Will be called by
 172      * {@code compute()} and the result passed to @{code setLocalResult()}
 173      *
 174      * @return the computed result of a leaf node
 175      */
 176     protected abstract R doLeaf();
 177 
 178     /**
 179      * Returns a suggested target leaf size based on the initial size estimate.
 180      *
 181      * @return suggested target leaf size
 182      */
 183     public static long suggestTargetSize(long sizeEstimate) {
 184         long est = sizeEstimate / LEAF_TARGET;
 185         return est > 0L ? est : 1L;
 186     }
 187 
 188     /**
 189      * Returns the targetSize, initializing it via the supplied
 190      * size estimate if not already initialized.
 191      */
 192     protected final long getTargetSize(long sizeEstimate) {
 193         long s;
 194         return ((s = targetSize) != 0 ? s :
 195                 (targetSize = suggestTargetSize(sizeEstimate)));
 196     }
 197 
 198     /**
 199      * Returns the local result, if any. Subclasses should use
 200      * {@link #setLocalResult(Object)} and {@link #getLocalResult()} to manage
 201      * results.  This returns the local result so that calls from within the
 202      * fork-join framework will return the correct result.
 203      *
 204      * @return local result for this node previously stored with


   1 /*
   2  * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util.stream;
  26 
  27 import java.util.Spliterator;
  28 import java.util.concurrent.CountedCompleter;
  29 import java.util.concurrent.ForkJoinPool;
  30 import java.util.concurrent.ForkJoinWorkerThread;
  31 
  32 /**
  33  * Abstract base class for most fork-join tasks used to implement stream ops.
  34  * Manages splitting logic, tracking of child tasks, and intermediate results.
  35  * Each task is associated with a {@link Spliterator} that describes the portion
  36  * of the input associated with the subtree rooted at this task.
  37  * Tasks may be leaf nodes (which will traverse the elements of
  38  * the {@code Spliterator}) or internal nodes (which split the
  39  * {@code Spliterator} into multiple child tasks).
  40  *
  41  * @implNote
  42  * <p>This class is based on {@link CountedCompleter}, a form of fork-join task
  43  * where each task has a semaphore-like count of uncompleted children, and the
  44  * task is implicitly completed and notified when its last child completes.
  45  * Internal node tasks will likely override the {@code onCompletion} method from
  46  * {@code CountedCompleter} to merge the results from child tasks into the
  47  * current task's result.
  48  *
  49  * <p>Splitting and setting up the child task links is done by {@code compute()}
  50  * for internal nodes.  At {@code compute()} time for leaf nodes, it is


  72  *             setLocalResult(result);
  73  *         }
  74  *     }
  75  * }</pre>
  76  *
  77  * <p>Serialization is not supported as there is no intention to serialize
  78  * tasks managed by stream ops.
  79  *
  80  * @param <P_IN> Type of elements input to the pipeline
  81  * @param <P_OUT> Type of elements output from the pipeline
  82  * @param <R> Type of intermediate result, which may be different from operation
  83  *        result type
  84  * @param <K> Type of parent, child and sibling tasks
  85  * @since 1.8
  86  */
  87 @SuppressWarnings("serial")
  88 abstract class AbstractTask<P_IN, P_OUT, R,
  89                             K extends AbstractTask<P_IN, P_OUT, R, K>>
  90         extends CountedCompleter<R> {
  91 
  92     private static final int LEAF_TARGET = ForkJoinPool.getCommonPoolParallelism() << 2;






  93 
  94     /** The pipeline helper, common to all tasks in a computation */
  95     protected final PipelineHelper<P_OUT> helper;
  96 
  97     /**
  98      * The spliterator for the portion of the input associated with the subtree
  99      * rooted at this task
 100      */
 101     protected Spliterator<P_IN> spliterator;
 102 
 103     /** Target leaf size, common to all tasks in a computation */
 104     protected long targetSize; // may be lazily initialized
 105 
 106     /**
 107      * The left child.
 108      * null if no children
 109      * if non-null rightChild is non-null
 110      */
 111     protected K leftChild;
 112 


 135         this.spliterator = spliterator;
 136         this.targetSize = 0L;
 137     }
 138 
 139     /**
 140      * Constructor for non-root nodes.
 141      *
 142      * @param parent this node's parent task
 143      * @param spliterator {@code Spliterator} describing the subtree rooted at
 144      *        this node, obtained by splitting the parent {@code Spliterator}
 145      */
 146     protected AbstractTask(K parent,
 147                            Spliterator<P_IN> spliterator) {
 148         super(parent);
 149         this.spliterator = spliterator;
 150         this.helper = parent.helper;
 151         this.targetSize = parent.targetSize;
 152     }
 153 
 154     /**
 155      * Default target of leaf tasks for parallel decomposition.
 156      * To allow load balancing, we over-partition, currently to approximately
 157      * four tasks per processor, which enables others to help out
 158      * if leaf tasks are uneven or some processors are otherwise busy.
 159      */
 160     public static int getLeafTarget() {
 161         Thread t = Thread.currentThread();
 162         if (t instanceof ForkJoinWorkerThread) {
 163             return ((ForkJoinWorkerThread) t).getPool().getParallelism() << 2;
 164         }
 165         else {
 166             return LEAF_TARGET;
 167         }
 168     }
 169 
 170     /**
 171      * Constructs a new node of type T whose parent is the receiver; must call
 172      * the AbstractTask(T, Spliterator) constructor with the receiver and the
 173      * provided Spliterator.
 174      *
 175      * @param spliterator {@code Spliterator} describing the subtree rooted at
 176      *        this node, obtained by splitting the parent {@code Spliterator}
 177      * @return newly constructed child node
 178      */
 179     protected abstract K makeChild(Spliterator<P_IN> spliterator);
 180 
 181     /**
 182      * Computes the result associated with a leaf node.  Will be called by
 183      * {@code compute()} and the result passed to @{code setLocalResult()}
 184      *
 185      * @return the computed result of a leaf node
 186      */
 187     protected abstract R doLeaf();
 188 
 189     /**
 190      * Returns a suggested target leaf size based on the initial size estimate.
 191      *
 192      * @return suggested target leaf size
 193      */
 194     public static long suggestTargetSize(long sizeEstimate) {
 195         long est = sizeEstimate / getLeafTarget();
 196         return est > 0L ? est : 1L;
 197     }
 198 
 199     /**
 200      * Returns the targetSize, initializing it via the supplied
 201      * size estimate if not already initialized.
 202      */
 203     protected final long getTargetSize(long sizeEstimate) {
 204         long s;
 205         return ((s = targetSize) != 0 ? s :
 206                 (targetSize = suggestTargetSize(sizeEstimate)));
 207     }
 208 
 209     /**
 210      * Returns the local result, if any. Subclasses should use
 211      * {@link #setLocalResult(Object)} and {@link #getLocalResult()} to manage
 212      * results.  This returns the local result so that calls from within the
 213      * fork-join framework will return the correct result.
 214      *
 215      * @return local result for this node previously stored with


< prev index next >