what is the difference between a stateful and a stateless lambda expression?

前端 未结 5 1111
北荒
北荒 2021-01-12 10:22

According to the OCP book one must avoid stateful operations otherwise known as stateful lambda expression. The definition provided in the book is \'a stateful lambda expres

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 10:58

    A stateful lambda expression is one whose result depends on any state that might change during the execution of a stream pipeline.

    Let's understand this with an example here:

        List list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
        List result = new ArrayList();
    
        list.parallelStream().map(s -> {
                synchronized (result) {
                  if (result.size() < 10) {
                    result.add(s);
                  }
                }
                return s;
            }).forEach( e -> {});
         System.out.println(result);  
    

    When you run this code 5 times, the output would/could be different all the time. Reason behind is here processing of Lambda expression inside map updates result array. Since here the result array depend on the size of that array for a particular sub stream, which would change every time this parallel stream would be called.

    For better understanding of parallel stream: Parallel computing involves dividing a problem into subproblems, solving those problems simultaneously (in parallel, with each subproblem running in a separate thread), and then combining the results of the solutions to the subproblems. When a stream executes in parallel, the Java runtime partitions the streams into multiple substreams. Aggregate operations iterate over and process these substreams in parallel and then combine the results.

    Hope this helps!!!

提交回复
热议问题