Issue with Java 8 Lambda for effective final while incrementing counts

后端 未结 3 1328
走了就别回头了
走了就别回头了 2021-01-26 17:04

I want to use Java 8 Lambda expression in following scenario but I am getting Local variable fooCount defined in an enclosing scope must be final or effectively final.

3条回答
  •  醉酒成梦
    2021-01-26 18:10

    I agree with the other answers indicating you should use countor partitioningBy.

    Just to explain the atomicity problem with an example, consider the following code:

    private static AtomicInteger i1 = new AtomicInteger(0);
    private static int i2 = 0;
    
    public static void main(String[] args) {
        IntStream.range(0, 100000).parallel().forEach(n -> i1.incrementAndGet());
        System.out.println(i1);
    
        IntStream.range(0, 100000).parallel().forEach(n -> i2++);
        System.out.println(i2);
    }
    

    This returns the expected result of 100000 for i1 but an indeterminate number less than that (between 50000 and 80000 in my test runs) for i2. The reason should be pretty obvious.

提交回复
热议问题