今天学ForkJoinPool时看到如下这段代码:
public static void main(String[] args) {
long[] numbers = LongStream.rangeClosed(1, 10000000).toArray();
Instant start = Instant.now();
Calculator calculator = new ForLoopCalculator();
long result = calculator.sumUp(numbers);
Instant end = Instant.now();
System.out.println("耗时:" + Duration.between(start, end).toMillis() + "ms");
System.out.println("结果为:" + result);
}
参考来源:和主管怼了一下午的ForkJoinPool - 知乎
对以下这一行代码产生了兴趣,去看了一下源码的实现。
LongStream.rangeClosed(1, 10000000).toArray();
源码实现如下(作为参考,LongStream.range() 的区别是左闭右开):
/**
* Returns a sequential ordered {@code LongStream} from {@code startInclusive}
* (inclusive) to {@code endInclusive} (inclusive) by an incremental step of
* {@code 1}.
*
* @apiNote
* <p>An equivalent sequence of increasing values can be produced
* sequentially using a {@code for} loop as follows:
* <pre>{@code
* for (long i = startInclusive; i <= endInclusive ; i++) { ... }
* }</pre>
*
* @param startInclusive the (inclusive) initial value
* @param endInclusive the inclusive upper bound
* @return a sequential {@code LongStream} for the range of {@code long}
* elements
*/
public static LongStream rangeClosed(long startInclusive, final long endInclusive) {
if (startInclusive > endInclusive) {
return empty();
} else if (endInclusive - startInclusive + 1 <= 0) {
// Size of range > Long.MAX_VALUE
// Split the range in two and concatenate
// Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then
// the lower range, [Long.MIN_VALUE, 0), and upper range,
// [0, Long.MAX_VALUE], will both be further split in two
long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1;
return concat(range(startInclusive, m), rangeClosed(m, endInclusive));
} else {
return StreamSupport.longStream(
new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false);
}
}
其中 endInclusive - startInclusive + 1 <= 0 的实现令人感叹(也许是我少见多怪),简而言之就是这样判断了一下范围是否超过了int的范围。
然后看了一下RangeLongSpliterator的实现如下:
RangeLongSpliterator(long from, long upTo, boolean closed) {
this(from, upTo, closed ? 1 : 0);
}
private RangeLongSpliterator(long from, long upTo, int last) {
assert upTo - from + last > 0;
this.from = from;
this.upTo = upTo;
this.last = last;
}
其中assert关键词
assert [boolean 表达式]
- 如果[boolean表达式]为true,则程序继续执行。
- 如果为false,则程序抛出AssertionError,并终止执行。
参考来源:Java中assert(断言)的使用_java assert_jeikerxiao的博客-CSDN博客
另外最初的代码中使用的Instant是Java8的新特性,参考: