src/java.base/share/classes/java/util/AbstractSplittableRng.java
branchJDK-8193209-branch
changeset 57436 b0c958c0e6c6
parent 57435 9a4184201823
child 57437 f02ffcb61dce
equal deleted inserted replaced
57435:9a4184201823 57436:b0c958c0e6c6
     1 /*
       
     2  * Copyright (c) 2013, 2019, 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;
       
    26 
       
    27 import java.util.function.Consumer;
       
    28 import java.util.function.IntConsumer;
       
    29 import java.util.function.LongConsumer;
       
    30 import java.util.function.DoubleConsumer;
       
    31 import java.util.Spliterator;
       
    32 import java.util.stream.StreamSupport;
       
    33 import java.util.stream.Stream;
       
    34 
       
    35 /**
       
    36  * This class provides much of the implementation of the {@code SplittableRng}
       
    37  * interface, to minimize the effort required to implement this interface.
       
    38  *
       
    39  * To implement a pseudorandom number generator, the programmer needs
       
    40  * only to extend this class and provide implementations for the
       
    41  * methods {@code nextInt()}, {@code nextLong()}, {@code period()},
       
    42  * and {@code split(SplittableRng)}.
       
    43  *
       
    44  * (If the pseudorandom number generator also has the ability to jump,
       
    45  * then the programmer may wish to consider instead extending
       
    46  * the class {@code AbstractSplittableJumpableRng} or (if it can also leap)
       
    47  * {@code AbstractSplittableLeapableRng}.  But if the pseudorandom number
       
    48  * generator furthermore has the ability to jump an arbitrary specified
       
    49  * distance, then the programmer may wish to consider instead extending
       
    50  * the class {@code * AbstractSplittableArbitrarilyJumpableRng}.)
       
    51  *
       
    52  * The programmer should generally provide at least three constructors:
       
    53  * one that takes no arguments, one that accepts a {@code long}
       
    54  * seed value, and one that accepts an array of seed {@code byte} values.
       
    55  * This class provides a public {@code initialSeed()} method that may
       
    56  * be useful in initializing some static state from which to derive
       
    57  * defaults seeds for use by the no-argument constructor.
       
    58  *
       
    59  * For the stream methods (such as {@code ints()} and {@code splits()}),
       
    60  * this class provides {@code Spliterator}-based implementations that
       
    61  * allow parallel execution when appropriate.
       
    62  *
       
    63  * The documentation for each non-abstract method in this class
       
    64  * describes its implementation in detail. Each of these methods may
       
    65  * be overridden if the pseudorandom number generator being
       
    66  * implemented admits a more efficient implementation.
       
    67  *
       
    68  * @author  Guy Steele
       
    69  * @author  Doug Lea
       
    70  * @since   1.9
       
    71  */
       
    72 public abstract class AbstractSplittableRng extends AbstractSpliteratorRng implements SplittableRng {
       
    73 
       
    74     /*
       
    75      * Implementation Overview.
       
    76      *
       
    77      * This class provides most of the "user API" methods needed to
       
    78      * satisfy the interface java.util.JumpableRng.  Most of these methods
       
    79      * are in turn inherited from AbstractRng and the non-public class
       
    80      * AbstractSpliteratorRng; this file implements two versions of the
       
    81      * splits method and defines the spliterators necessary to support
       
    82      * them.
       
    83      *
       
    84      * The abstract split() method from interface SplittableRng is redeclared
       
    85      * here so as to narrow the return type to AbstractSplittableRng.
       
    86      *
       
    87      * File organization: First the non-public methods needed by the class
       
    88      * AbstractSpliteratorRng, then the main public methods, followed by some
       
    89      * custom spliterator classes.
       
    90      */
       
    91 
       
    92     Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound) {
       
    93 	return new RandomIntsSpliterator(this, index, fence, origin, bound);
       
    94     }
       
    95     
       
    96     Spliterator.OfLong makeLongsSpliterator(long index, long fence, long origin, long bound) {
       
    97 	return new RandomLongsSpliterator(this, index, fence, origin, bound);
       
    98     }
       
    99     
       
   100     Spliterator.OfDouble makeDoublesSpliterator(long index, long fence, double origin, double bound) {
       
   101 	return new RandomDoublesSpliterator(this, index, fence, origin, bound);
       
   102     }
       
   103 
       
   104     Spliterator<SplittableRng> makeSplitsSpliterator(long index, long fence, SplittableRng source) {
       
   105 	return new RandomSplitsSpliterator(source, index, fence, this);
       
   106     }
       
   107 
       
   108     /* ---------------- public methods ---------------- */
       
   109 
       
   110     /**
       
   111      * Implements the @code{split()} method as {@code this.split(this) }.
       
   112      *
       
   113      * @return the new {@code AbstractSplittableRng} instance
       
   114      */
       
   115     public SplittableRng split() { return this.split(this); }
       
   116     
       
   117     // Stream methods for splittings
       
   118 
       
   119     /**
       
   120      * Returns an effectively unlimited stream of new pseudorandom
       
   121      * number generators, each of which implements the {@code SplittableRng}
       
   122      * interface.
       
   123      *
       
   124      * This pseudorandom number generator provides the
       
   125      * entropy used to seed the new ones.
       
   126      *
       
   127      * @implNote This method is implemented to be equivalent to
       
   128      * {@code splits(Long.MAX_VALUE)}.
       
   129      *
       
   130      * @return a stream of {@code SplittableRng} objects
       
   131      */
       
   132     public Stream<SplittableRng> splits() {
       
   133         return this.splits(Long.MAX_VALUE, this);
       
   134     }
       
   135 
       
   136     /**
       
   137      * Returns a stream producing the given {@code streamSize} number of
       
   138      * new pseudorandom number generators, each of which implements the
       
   139      * {@code SplittableRng} interface.
       
   140      *
       
   141      * This pseudorandom number generator provides the
       
   142      * entropy used to seed the new ones.
       
   143      *
       
   144      * @param streamSize the number of values to generate
       
   145      * @return a stream of {@code SplittableRng} objects
       
   146      * @throws IllegalArgumentException if {@code streamSize} is
       
   147      *         less than zero
       
   148      */
       
   149     public Stream<SplittableRng> splits(long streamSize) {
       
   150 	return this.splits(streamSize, this);
       
   151     }
       
   152 
       
   153     /**
       
   154      * Returns an effectively unlimited stream of new pseudorandom
       
   155      * number generators, each of which implements the {@code SplittableRng}
       
   156      * interface.
       
   157      *
       
   158      * @implNote This method is implemented to be equivalent to
       
   159      * {@code splits(Long.MAX_VALUE)}.
       
   160      *
       
   161      * @param source a {@code SplittableRng} instance to be used instead
       
   162      *               of this one as a source of pseudorandom bits used to
       
   163      *               initialize the state of the new ones.
       
   164      * @return a stream of {@code SplittableRng} objects
       
   165      */
       
   166     public Stream<SplittableRng> splits(SplittableRng source) {
       
   167         return this.splits(Long.MAX_VALUE, source);
       
   168     }
       
   169 
       
   170     /**
       
   171      * Returns a stream producing the given {@code streamSize} number of
       
   172      * new pseudorandom number generators, each of which implements the
       
   173      * {@code SplittableRng} interface.
       
   174      *
       
   175      * @param streamSize the number of values to generate
       
   176      * @param source a {@code SplittableRng} instance to be used instead
       
   177      *               of this one as a source of pseudorandom bits used to
       
   178      *               initialize the state of the new ones.
       
   179      * @return a stream of {@code SplittableRng} objects
       
   180      * @throws IllegalArgumentException if {@code streamSize} is
       
   181      *         less than zero
       
   182      */
       
   183     public Stream<SplittableRng> splits(long streamSize, SplittableRng source) {
       
   184 	RngSupport.checkStreamSize(streamSize);
       
   185         return StreamSupport.stream(makeSplitsSpliterator(0L, streamSize, source), false);
       
   186     }
       
   187         
       
   188     /**
       
   189      * Spliterator for int streams.  We multiplex the four int
       
   190      * versions into one class by treating a bound less than origin as
       
   191      * unbounded, and also by treating "infinite" as equivalent to
       
   192      * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
       
   193      * approach. The long and double versions of this class are
       
   194      * identical except for types.
       
   195      */
       
   196     static class RandomIntsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfInt {
       
   197 	final SplittableRng generatingRng;
       
   198         final int origin;
       
   199         final int bound;
       
   200 
       
   201         RandomIntsSpliterator(SplittableRng generatingRng, long index, long fence, int origin, int bound) {
       
   202 	    super(index, fence);
       
   203 	    this.generatingRng = generatingRng;
       
   204             this.origin = origin; this.bound = bound;
       
   205         }
       
   206 	
       
   207         public Spliterator.OfInt trySplit() {
       
   208             long i = index, m = (i + fence) >>> 1;
       
   209 	    if (m <= i) return null;
       
   210 	    index = m;
       
   211 	    return new RandomIntsSpliterator(generatingRng.split(), i, m, origin, bound);
       
   212         }
       
   213 
       
   214         public boolean tryAdvance(IntConsumer consumer) {
       
   215             if (consumer == null) throw new NullPointerException();
       
   216             long i = index, f = fence;
       
   217             if (i < f) {
       
   218                 consumer.accept(RngSupport.boundedNextInt(generatingRng, origin, bound));
       
   219                 index = i + 1;
       
   220                 return true;
       
   221             }
       
   222             else return false;
       
   223         }
       
   224 
       
   225         public void forEachRemaining(IntConsumer consumer) {
       
   226             if (consumer == null) throw new NullPointerException();
       
   227             long i = index, f = fence;
       
   228             if (i < f) {
       
   229                 index = f;
       
   230                 Rng r = generatingRng;
       
   231                 int o = origin, b = bound;
       
   232                 do {
       
   233                     consumer.accept(RngSupport.boundedNextInt(r, o, b));
       
   234                 } while (++i < f);
       
   235             }
       
   236         }
       
   237     }
       
   238 
       
   239     /**
       
   240      * Spliterator for long streams.
       
   241      */
       
   242     static class RandomLongsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfLong {
       
   243 	final SplittableRng generatingRng;
       
   244         final long origin;
       
   245         final long bound;
       
   246 
       
   247         RandomLongsSpliterator(SplittableRng generatingRng, long index, long fence, long origin, long bound) {
       
   248 	    super(index, fence);
       
   249 	    this.generatingRng = generatingRng;
       
   250             this.origin = origin; this.bound = bound;
       
   251         }
       
   252 	
       
   253         public Spliterator.OfLong trySplit() {
       
   254             long i = index, m = (i + fence) >>> 1;
       
   255 	    if (m <= i) return null;
       
   256 	    index = m;
       
   257 	    return new RandomLongsSpliterator(generatingRng.split(), i, m, origin, bound);
       
   258         }
       
   259 
       
   260         public boolean tryAdvance(LongConsumer consumer) {
       
   261             if (consumer == null) throw new NullPointerException();
       
   262             long i = index, f = fence;
       
   263             if (i < f) {
       
   264                 consumer.accept(RngSupport.boundedNextLong(generatingRng, origin, bound));
       
   265                 index = i + 1;
       
   266                 return true;
       
   267             }
       
   268             else return false;
       
   269         }
       
   270 
       
   271         public void forEachRemaining(LongConsumer consumer) {
       
   272             if (consumer == null) throw new NullPointerException();
       
   273             long i = index, f = fence;
       
   274             if (i < f) {
       
   275                 index = f;
       
   276                 Rng r = generatingRng;
       
   277                 long o = origin, b = bound;
       
   278                 do {
       
   279                     consumer.accept(RngSupport.boundedNextLong(r, o, b));
       
   280                 } while (++i < f);
       
   281             }
       
   282         }
       
   283     }
       
   284 
       
   285     /**
       
   286      * Spliterator for double streams.
       
   287      */
       
   288     static class RandomDoublesSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfDouble {
       
   289 	final SplittableRng generatingRng;
       
   290         final double origin;
       
   291         final double bound;
       
   292 
       
   293         RandomDoublesSpliterator(SplittableRng generatingRng, long index, long fence, double origin, double bound) {
       
   294 	    super(index, fence);
       
   295 	    this.generatingRng = generatingRng;
       
   296             this.origin = origin; this.bound = bound;
       
   297         }
       
   298 	
       
   299         public Spliterator.OfDouble trySplit() {
       
   300             long i = index, m = (i + fence) >>> 1;
       
   301 	    if (m <= i) return null;
       
   302 	    index = m;
       
   303 	    return new RandomDoublesSpliterator(generatingRng.split(), i, m, origin, bound);
       
   304         }
       
   305 
       
   306         public boolean tryAdvance(DoubleConsumer consumer) {
       
   307             if (consumer == null) throw new NullPointerException();
       
   308             long i = index, f = fence;
       
   309             if (i < f) {
       
   310                 consumer.accept(RngSupport.boundedNextDouble(generatingRng, origin, bound));
       
   311                 index = i + 1;
       
   312                 return true;
       
   313             }
       
   314             else return false;
       
   315         }
       
   316 
       
   317         public void forEachRemaining(DoubleConsumer consumer) {
       
   318             if (consumer == null) throw new NullPointerException();
       
   319             long i = index, f = fence;
       
   320             if (i < f) {
       
   321                 index = f;
       
   322                 Rng r = generatingRng;
       
   323                 double o = origin, b = bound;
       
   324                 do {
       
   325                     consumer.accept(RngSupport.boundedNextDouble(r, o, b));
       
   326                 } while (++i < f);
       
   327             }
       
   328         }
       
   329     }
       
   330 
       
   331     /**
       
   332      * Spliterator for stream of generators of type SplittableRng.  We multiplex the two
       
   333      * versions into one class by treating "infinite" as equivalent to Long.MAX_VALUE.
       
   334      * For splits, it uses the standard divide-by-two approach.
       
   335      */
       
   336     static class RandomSplitsSpliterator extends RngSupport.RandomSpliterator implements Spliterator<SplittableRng> {
       
   337 	final SplittableRng generatingRng;
       
   338 	final SplittableRng constructingRng;
       
   339 
       
   340         RandomSplitsSpliterator(SplittableRng generatingRng, long index, long fence, SplittableRng constructingRng) {
       
   341 	    super(index, fence);
       
   342 	    this.generatingRng = generatingRng;
       
   343 	    this.constructingRng = constructingRng;
       
   344         }
       
   345 	
       
   346         public Spliterator<SplittableRng> trySplit() {
       
   347             long i = index, m = (i + fence) >>> 1;
       
   348 	    if (m <= i) return null;
       
   349 	    index = m;
       
   350 	    return new RandomSplitsSpliterator(generatingRng.split(), i, m, constructingRng);
       
   351         }
       
   352 
       
   353         public boolean tryAdvance(Consumer<? super SplittableRng> consumer) {
       
   354             if (consumer == null) throw new NullPointerException();
       
   355             long i = index, f = fence;
       
   356             if (i < f) {
       
   357                 consumer.accept(constructingRng.split(generatingRng));
       
   358                 index = i + 1;
       
   359                 return true;
       
   360             }
       
   361             else return false;
       
   362         }
       
   363 
       
   364         public void forEachRemaining(Consumer<? super SplittableRng> consumer) {
       
   365             if (consumer == null) throw new NullPointerException();
       
   366             long i = index, f = fence;
       
   367             if (i < f) {
       
   368                 index = f;
       
   369 		SplittableRng c = constructingRng;
       
   370                 SplittableRng r = generatingRng;
       
   371                 do {
       
   372                     consumer.accept(c.split(r));
       
   373                 } while (++i < f);
       
   374             }
       
   375         }
       
   376     }
       
   377 
       
   378 }