发散思维的学习笔记

今天学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的新特性,参考:

Java8 新特性 - Instant 时间戳类_toepochmilli_NorthCastle的博客-CSDN博客 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值