Skip to content

Instantly share code, notes, and snippets.

@debu999
Last active September 8, 2022 05:54
Show Gist options
  • Save debu999/c26438bc3459c967646208f412e493b8 to your computer and use it in GitHub Desktop.
Save debu999/c26438bc3459c967646208f412e493b8 to your computer and use it in GitHub Desktop.
Stream -> .parallel()
ParallelStream -> sequential()
pool induced deadlock java fixed with fork join pool with work stealing
parallelstream uses java 7 forkjoinpool (Common ForkJoinPool)
forEachOrdered and forEach are 2 options. forEachOrdered is not sequentional. ForEachOrdered gurantees imposed order viz. if
list order then then it will work. But set cant have a ordering.
stream - > parallel -> map and filter runs in threads.
reduce have the option to have identity value for sum its 0 for multiply/div its 1.
So what we work with must be a monoid.
How many threads should i create deends on computation innensive vs io intensisve
for computantion intensive #thread <= # core and for io intensiv #Thread may be > # cores
# of Cores
#T <= --------------------------
1 - blocking factoor
0 <= blocking factor < 1
usually its core - 1 for parallelism
if you want then its -Djava.util.concurrent.ForkJoinPool.common.parallelism=100R
Reactive Streams have Data / Error / Completed chnnels
Completed futres = isees
Functional interfaces
Supplier<T> T get(); //factories
Consumer<T> void accept(); //forEach //thenAccept
Predicate<T> boolean test(T); //filter
Function<T,R> R apply(T); //map
future.get() //blocking
future.getNow(0) //NonBlocking its because if you do not have result then it returns 0
supplyAsync() <- with or without pool run in thread
CompleteableFuture Streams
lazy lazy
thenAccept (returns CF<void> forEach
thenApply (returns CF) map
thenRun (returns CF custom) XXX
0 or 1 0 , 1 or more data
data/error channel only data channel
error channel. exceptions -- oops handle them
thenCombine(if another cf is returned) flatmap
thenAccept returns another completable future (forEach)
thenApply (transformation like map in streams)
thenRun (returns completable future sequential flow in CF)
Exceptionally throwable to response
find nearest then for data and nearest exceptionally for exception
future.complete(data) and future.completeExceptionally(Throwable)
future.completeOnTimeout(initialvalue, 1, Timeunit.SECONDS)
future.orTimeout(initialvalue, 1, Timeunit.SECONDS)
public CompleteableFuture<Integer> createFuture(int num){
return CompleteableFuture.supplyAsynce(()-> num);
}
CompleteableFuture<Integer> fut = createFuture(2);
fut.thenCompose(createFuture(2),(r1,r2) -> r1+r2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment