SlideShare a Scribd company logo
Java 8 Streams
Srinivasan Raghavan
Senior Member of Technical Staff
Java Platform Group
What's all about …………………….
This presentation gives more insight how the streams api are implemented
under the hood .
This can give more insight into what library developers and app developers are
using
Design involved in Streams api
● The building block of the stream is computer science concept called pipeline .
● A pipeline is concept when the output of one of the one unit of the work is the input of the other
● Streams api use this concept to provide powerful interfaces for manipulating the data stored in
collections
● Streams api is built around functional interfaces new introduction to java 8 in java.util.function*
● Functional interfaces provides along with lambdas provide great opportunity for behavior driven
development
Functional Interface
● A functional interface can have only abstract method
● Other methods can be declared but it can default and should have a base implementation
● Lambda can be used only with functional interface
java.util.function*
Function<T, R>
Takes an input and gives an output
R apply(T t);
default funtion compose(Function<? super V, ? extends T> before)
evaluates the bef0re ands applies the result to the current
default function andThen(Function<? super R, ? extends V> after)
evaluates the current apply and input the after.apply()
More functions
BiFunction<T, U, R>
takes two inputs and gives an output
and the default fn and then evaluates bifunction and applies the output to the after
function ie after.apply()
Predicate<T>
A predicate take an input performs a test and supplies boolean and(Predicate<T>
predicate)
Returns a composed predicate that represents a short-circuiting logical AND of this
predicate and another.
negate
Returns a predicate that represents the logical negation of this predicate
or(Predicate<T> predicate)
returns or short circuiting
isEqual(Object ref)
Returns a predicate that tests if two arguments are equal according
Consumer<T>
A consumer consumes a values and return nothing nothing and then accepts the current
andthe after.accepts
Spliterator
● Spliterator Interface design is means of achieving pipelined access to the data structure
● A Split Iterator can advance through the block of data individually tryAdance() or in a bulk forEachRemaining()
and can split trySplit() into another Spliterator
● It has a series of characteristics represented by masks which indicates to the client of the spilt iterator so that
client write the behaviour according to that
● Some of these are ORDERED DISTINCT SORTED CONCURRENT IMMUTABLE
● Characteristics like order makes the code traversing conforming to order
● The split iterator also detects for concurrent modification if it does not have the characteristics CONCURRENT
and IMMUTABLE .
● A late binding Spliterator can bind to elements in collection when the first tryAdvance(), trySplit() id called.
● An non late binding can attach to the source at invocation on of any method of the split iterator
Spliterator
● As an example how a parallel computation framework, such as the {@code java.util.stream} package, would use Spliterator in a
parallel computation
● if we assume that the order of processing across subtasks doesn't matter; different (forked) tasks may further split and process
elements concurrently in undetermined order.
static class ParEach<T> extends CountedCompleter<Void> {
final Spliterator<T> spliterator;
final Consumer<T> action;
final long targetBatchSize;
ParEach(ParEach<T> parent, Spliterator<T> spliterator,
Consumer<T> action, long targetBatchSize) {
super(parent);
this.spliterator = spliterator; this.action = action;
this.targetBatchSize = targetBatchSize;
}
public void compute() {
Spliterator<T> sub;
while (spliterator.estimateSize() > targetBatchSize &&
(sub = spliterator.trySplit()) != null) {
addToPendingCount(1);
new ParEach<>(this, sub, action, targetBatchSize).fork();
}
spliterator.forEachRemaining(action);
propagateCompletion();
How the reference pipeline works?
● The basic data structure involved is a linked list of pipe stages .
● The pipe stages are initiated with a Head when the stream is initialized
● The when an ops like filter , map or reduce is added the pipe stages are added on a linked list
● the ops like filter(Predicate<? super P_OUT> predicate) map(Function<? super P_OUT, ? extends R> mapper)
flatMap(Function<? super P_OUT, ? extends Stream<? extends R>> mapper) are intermediate stages
● the terminal ops are reduce(final P_OUT identity, final BinaryOperator<P_OUT> accumulator)
,collect(Collector<? super P_OUT, A, R> collector) and forEach(Consumer<? super P_OUT> action)
● So when the terminal stages are added the code evaluates whether the ops can be parallelised and then start
the call the spliterator code and apply all the behaviours in the sequentially
Parallelisation of ops
● Each stages of the pipeline can be parallelized if the spliterator implementation and order is not required for the
execution
● So how parallel ops work . There is a method called trysplit() in spliterator which splits the data structure into two
● These two can be further split if that data is long enough and supplied the fork join common pool .
● So the fork join uses a counted completer for computing each split and compute parallel
● There is a eval parallel which evaluates the contention in the common pool before doing a fork join .
● So parallel is not guaranteed to work cause if allowed for the developer control . Careless implementation can
cause overload and less throughput

More Related Content

What's hot

Memory allocation
Memory allocationMemory allocation
Memory allocation
sanya6900
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Simon Ritter
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
Jim Bethancourt
 
Storage Class Specifiers
Storage Class SpecifiersStorage Class Specifiers
Storage Class Specifiers
Reddhi Basu
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
Asankhaya Sharma
 
Java 8
Java 8Java 8
Java 8vpulec
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
 
Mikio Braun – Data flow vs. procedural programming
Mikio Braun – Data flow vs. procedural programming Mikio Braun – Data flow vs. procedural programming
Mikio Braun – Data flow vs. procedural programming
Flink Forward
 
Deploying Microservice on Docker
Deploying Microservice on DockerDeploying Microservice on Docker
Deploying Microservice on Docker
Knoldus Inc.
 
Link quries
Link quriesLink quries
Link quries
ulfat mushtaq
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
RichardWarburton
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
Roberto Casadei
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
Shashank L
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
Takipi
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Re-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for XtextRe-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for Xtext
Edward Willink
 

What's hot (20)

Memory allocation
Memory allocationMemory allocation
Memory allocation
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Storage Class Specifiers
Storage Class SpecifiersStorage Class Specifiers
Storage Class Specifiers
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
 
Java 8
Java 8Java 8
Java 8
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Mikio Braun – Data flow vs. procedural programming
Mikio Braun – Data flow vs. procedural programming Mikio Braun – Data flow vs. procedural programming
Mikio Braun – Data flow vs. procedural programming
 
Deploying Microservice on Docker
Deploying Microservice on DockerDeploying Microservice on Docker
Deploying Microservice on Docker
 
Link quries
Link quriesLink quries
Link quries
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
 
Unit 5
Unit 5Unit 5
Unit 5
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Re-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for XtextRe-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for Xtext
 
Scilab vs matlab
Scilab vs matlabScilab vs matlab
Scilab vs matlab
 

Similar to Java 8 streams

Lambda.pdf
Lambda.pdfLambda.pdf
Lambda.pdf
ManishWalia18
 
Apache Crunch
Apache CrunchApache Crunch
Apache Crunch
Alwin James
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programming
Araf Karsh Hamid
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Java 8
Java 8Java 8
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
VMware Tanzu
 
Lambdas : Beyond The Basics
Lambdas : Beyond The BasicsLambdas : Beyond The Basics
Lambdas : Beyond The Basics
Simon Ritter
 
Universal metrics with Apache Beam
Universal metrics with Apache BeamUniversal metrics with Apache Beam
Universal metrics with Apache Beam
Etienne Chauchot
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
Bansilal Haudakari
 
Java 8
Java 8Java 8
Java 8
vilniusjug
 
Apache airflow
Apache airflowApache airflow
Apache airflow
Purna Chander
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
 
Declarative Experimentation in Information Retrieval using PyTerrier
Declarative Experimentation in Information Retrieval using PyTerrierDeclarative Experimentation in Information Retrieval using PyTerrier
Declarative Experimentation in Information Retrieval using PyTerrier
Crai Macdonald
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
Indrajit Das
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
Geertjan Wielenga
 
Akka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaAkka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with Scala
Jerry Kuru
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 

Similar to Java 8 streams (20)

java8
java8java8
java8
 
Lambda.pdf
Lambda.pdfLambda.pdf
Lambda.pdf
 
Apache Crunch
Apache CrunchApache Crunch
Apache Crunch
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programming
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
 
Java 8
Java 8Java 8
Java 8
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
 
Lambdas : Beyond The Basics
Lambdas : Beyond The BasicsLambdas : Beyond The Basics
Lambdas : Beyond The Basics
 
Universal metrics with Apache Beam
Universal metrics with Apache BeamUniversal metrics with Apache Beam
Universal metrics with Apache Beam
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
 
Java 8
Java 8Java 8
Java 8
 
Apache airflow
Apache airflowApache airflow
Apache airflow
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Declarative Experimentation in Information Retrieval using PyTerrier
Declarative Experimentation in Information Retrieval using PyTerrierDeclarative Experimentation in Information Retrieval using PyTerrier
Declarative Experimentation in Information Retrieval using PyTerrier
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
Akka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaAkka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with Scala
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 

Recently uploaded

Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Yara Milbes
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 

Recently uploaded (20)

Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 

Java 8 streams

  • 1. Java 8 Streams Srinivasan Raghavan Senior Member of Technical Staff Java Platform Group
  • 2. What's all about ……………………. This presentation gives more insight how the streams api are implemented under the hood . This can give more insight into what library developers and app developers are using
  • 3. Design involved in Streams api ● The building block of the stream is computer science concept called pipeline . ● A pipeline is concept when the output of one of the one unit of the work is the input of the other ● Streams api use this concept to provide powerful interfaces for manipulating the data stored in collections ● Streams api is built around functional interfaces new introduction to java 8 in java.util.function* ● Functional interfaces provides along with lambdas provide great opportunity for behavior driven development
  • 4. Functional Interface ● A functional interface can have only abstract method ● Other methods can be declared but it can default and should have a base implementation ● Lambda can be used only with functional interface
  • 5. java.util.function* Function<T, R> Takes an input and gives an output R apply(T t); default funtion compose(Function<? super V, ? extends T> before) evaluates the bef0re ands applies the result to the current default function andThen(Function<? super R, ? extends V> after) evaluates the current apply and input the after.apply()
  • 6. More functions BiFunction<T, U, R> takes two inputs and gives an output and the default fn and then evaluates bifunction and applies the output to the after function ie after.apply() Predicate<T> A predicate take an input performs a test and supplies boolean and(Predicate<T> predicate) Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another. negate Returns a predicate that represents the logical negation of this predicate or(Predicate<T> predicate) returns or short circuiting isEqual(Object ref) Returns a predicate that tests if two arguments are equal according Consumer<T> A consumer consumes a values and return nothing nothing and then accepts the current andthe after.accepts
  • 7. Spliterator ● Spliterator Interface design is means of achieving pipelined access to the data structure ● A Split Iterator can advance through the block of data individually tryAdance() or in a bulk forEachRemaining() and can split trySplit() into another Spliterator ● It has a series of characteristics represented by masks which indicates to the client of the spilt iterator so that client write the behaviour according to that ● Some of these are ORDERED DISTINCT SORTED CONCURRENT IMMUTABLE ● Characteristics like order makes the code traversing conforming to order ● The split iterator also detects for concurrent modification if it does not have the characteristics CONCURRENT and IMMUTABLE . ● A late binding Spliterator can bind to elements in collection when the first tryAdvance(), trySplit() id called. ● An non late binding can attach to the source at invocation on of any method of the split iterator
  • 8. Spliterator ● As an example how a parallel computation framework, such as the {@code java.util.stream} package, would use Spliterator in a parallel computation ● if we assume that the order of processing across subtasks doesn't matter; different (forked) tasks may further split and process elements concurrently in undetermined order. static class ParEach<T> extends CountedCompleter<Void> { final Spliterator<T> spliterator; final Consumer<T> action; final long targetBatchSize; ParEach(ParEach<T> parent, Spliterator<T> spliterator, Consumer<T> action, long targetBatchSize) { super(parent); this.spliterator = spliterator; this.action = action; this.targetBatchSize = targetBatchSize; } public void compute() { Spliterator<T> sub; while (spliterator.estimateSize() > targetBatchSize && (sub = spliterator.trySplit()) != null) { addToPendingCount(1); new ParEach<>(this, sub, action, targetBatchSize).fork(); } spliterator.forEachRemaining(action); propagateCompletion();
  • 9. How the reference pipeline works? ● The basic data structure involved is a linked list of pipe stages . ● The pipe stages are initiated with a Head when the stream is initialized ● The when an ops like filter , map or reduce is added the pipe stages are added on a linked list ● the ops like filter(Predicate<? super P_OUT> predicate) map(Function<? super P_OUT, ? extends R> mapper) flatMap(Function<? super P_OUT, ? extends Stream<? extends R>> mapper) are intermediate stages ● the terminal ops are reduce(final P_OUT identity, final BinaryOperator<P_OUT> accumulator) ,collect(Collector<? super P_OUT, A, R> collector) and forEach(Consumer<? super P_OUT> action) ● So when the terminal stages are added the code evaluates whether the ops can be parallelised and then start the call the spliterator code and apply all the behaviours in the sequentially
  • 10. Parallelisation of ops ● Each stages of the pipeline can be parallelized if the spliterator implementation and order is not required for the execution ● So how parallel ops work . There is a method called trysplit() in spliterator which splits the data structure into two ● These two can be further split if that data is long enough and supplied the fork join common pool . ● So the fork join uses a counted completer for computing each split and compute parallel ● There is a eval parallel which evaluates the contention in the common pool before doing a fork join . ● So parallel is not guaranteed to work cause if allowed for the developer control . Careless implementation can cause overload and less throughput