Register a Stream “completion” hook

后端 未结 5 1297
长情又很酷
长情又很酷 2020-12-15 03:46

Using the Java 8 Stream API, I would like to register a \"completion hook\", along the lines of:

Stream stream = Stream.of(\"a\",          


        
5条回答
  •  我在风中等你
    2020-12-15 04:44

    The simplest solution is to wrap a stream in another stream and flatmap it to itself:

    // example stream
    Stream original=Stream.of("bla").onClose(()->System.out.println("close action"));
    
    // this is the trick
    Stream autoClosed=Stream.of(original).flatMap(Function.identity());
    
    //example op
    int sum=autoClosed.mapToInt(String::length).sum();
    System.out.println(sum);
    

    The reason why it works lies in the flatMap operation:

    Each mapped stream is closed after its contents have been placed into this stream.

    But the current implementation isn’t as lazy as it should be when using flatMap. This has been fixed in Java 10.


    My recommendation is to stay with the try(…) standard solution and document when a returned stream need to be closed. After all, a stream that closes the resource after the terminal operation isn’t safe as there is no guaranty that the client will actually invoke a terminal operation. Changing it’s mind and abandon a stream instant is a valid use, whereas not calling the close() method, when the documentation specifies that it is required, is not.

提交回复
热议问题