Posts

Showing posts from June, 2024

Process Java Collection in batches

The following snippets shows how to process a given Java Collection (List / Set) in batches and process each batch in sequence or parallel. Split a given collection into batches int batchSize = 2 ; List < String > input = List .of( "apple" , "banana" , "orange" , "mango" , "peach" ); List < List < String >> batches = IntStream .range( 0 , input . size ()) . boxed () . collect ( Collectors .groupingBy( index -> index / batchSize )) . values () . stream () . map ( indices -> indices . stream (). map ( input :: get ). toList ()) . toList (); batches . forEach ( values -> System . out . println ( "values = " + values )); Parallel process collection in batches using Java's ForkJoin.commonPool() int batchSize = 2 ; List < String > input = List .of( "apple" , "banana" , "orange" , "mango" , "peach" ); List < List

Java's CompletableFuture reference

 Since the addition of CompletableFuture in Java 8, running background task or parallel processing or multi-threading got really simplified. These are some of the examples on how to use CompletableFuture in standalone java or with Spring Boot to perform background tasks. Complete list of methods available in CompletableFuture can be found here at https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/CompletableFuture.html Basic example to call a method in background and return result The task gets executed in Java's default ForkJoin.commonPool() CompletableFuture < String > completableFuture = CompletableFuture .supplyAsync(() -> "Hello" ); String result = completableFuture . join (); System . out . println ( "result = " + result ); Basic example to call a method in background and without returning a result The task gets executed in Java's default ForkJoin.commonPool() CompletableFuture < Void > completableFuture