![](/img/trans.png)
[英]java-8 streams : Are new streams from intermediate operations returned without increase in memory?
[英]How to run only certain intermediate operations in parallel in Java-8?
我試圖模仿行為WireTap
在Spring Integration
和Apache Camel
在java8流,在當前處理數據的副本被傳遞到WireTap
在一個單獨的線程處理它,這將是用於記錄和審計有幫助
在這里,我只希望在peek
登錄才能在單獨的線程上運行
List<String> lines = ...
List<String> upperLines = lines.stream()
.map(String::toUpperCase)
.parallel() // which is hidden by the sequential
.peek(line -> System.out.println(line)) // don't want to run this fully on main thread
.sequential()
.collect(Collectors.toList());
我是否需要使用BlockingQueue
或ExecutorService
實現單獨的方法來執行此操作
.peek(this::logger)
沒有辦法在不同的模式下處理流管道的各個部分,並且給定這樣一個簡單的提交異步作業的方式,實現這樣的混合模式管道是無濟於事的:
ExecutorService es = Executors.newFixedThreadPool(4);
List<String> upperLines = lines.stream()
.map(String::toUpperCase)
.peek(line -> es.execute(() -> System.out.println(line)))
.collect(Collectors.toList());
es.shutdown();
要么
List<String> upperLines = lines.stream()
.map(String::toUpperCase)
.peek(line -> CompletableFuture.runAsync(() -> System.out.println(line)))
.collect(Collectors.toList());
// when running this in the main method, avoid JVM termination before the async jobs:
ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);
但是請注意,在這種特定情況下,實際上並沒有明顯的區別,例如
List<String> upperLines = lines.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
upperLines.parallelStream().forEach(line -> System.out.println(line));
或者,如果您不想等待日志記錄語句的完成,請執行以下操作:
List<String> upperLines = lines.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
upperLines.forEach(line -> CompletableFuture.runAsync(() -> System.out.println(line)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.