Java Lambda internals with invoke dynamic

mohitkumar965 18 views 145 slides Jun 18, 2024
Slide 1
Slide 1 of 145
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145

About This Presentation

How java lambda works


Slide Content

Behavior
Parameterization:Example-1

Behavior
Parameterization:Example-2

Behavior
Parameterization:Example-3

Behavior
Parameterization:Predicate

Behavior
Parameterization:Predicate

Behavior
Parameterization:Predicate:Example-3

Behavior Parameterization:Predicate

Behavior
Parameterization:Predicate:Multiple
Behavior one parameter

Behavior
Parameterization:Predicate:Anonymous
Classes

Behavior
Parameterization:Predicate:Anonymous
Classes

Behavior
Parameterization:Predicate:Lambda

Behavior
Parameterization:Predicate:Lambda

Behavior
Parameterization:Predicate:Lambda

Behavior
Parameterization:Predicate:Lambda

Lambda:Introduction
●A lambda expression can be understood as a concise representation of an
anonymous function that can be passed around: it doesn’t have a name, but it
has a list of parameters, a body, a return type, and also possibly a list of
exceptions that can be thrown. That’s one big definition;
–Anonymous— We say anonymous because it doesn’t have an explicit name
like a method would normally have: less to write and think about!
–Function— We say function because a lambda isn’t associated with a
particular class like a method is. But like a method, a lambda has a list of
parameters, a body, a return type, and a possible list of exceptions that can
be thrown.
–Passed around— A lambda expression can be passed as argument to a
method or stored in a variable.
–Concise— You don’t need to write a lot of boilerplate like you do for
anonymous classes.

Lambda:Introduction

Lambda:Introduction

Funtional Interfaces

Funtional Interfaces
●What can you do with functional interfaces?
–Lambda expressions let you provide the implementation of
the abstract method of a functional interface directly inline
and treat the whole expression as an instance of a functional
interface (more technically speaking, an instance of a
concrete implementation of the functional interface).
–You can achieve the same thing with an anonymous inner
class, although it’s clumsier

Funtional Interfaces

Lambda:Type Inference

Lambda:Local Variables

Method References

Method References

Method References

Constructor References

Constructor References

Constructor References

Lambda:Sorting

Lambda:Secondary Sorting

Lambda:Chaining Predicates

Lambda:Chaining Functions

Lambda:Chaining Functions

Streams

Streams

Streams:Software Engineering Benefits
●The code is written in a declarative way:
–you specify what you want to achieve (that is, filter dishes that are low in
calories) as opposed to specifying how to implement an operation (using
control-flow blocks such as loops and if conditions).
–Together with behavior parameterization, enables you to cope with
changing requirements: you could easily create an additional version of
your code to filter high-calorie dishes using a lambda expression, without
having to copy and paste code.
●You chain together several building-block operations to express a
complicated data processing pipeline while keeping your code readable and
its intent clear.
–The result of the filter is passed to the sorted method, which is then
passed to the map method and then to the collect method.

Streams:Software Engineering Benefits
●Because operations such as filter (or sorted, map, and collect)
are available as high-level building blocks that don’t depend on
a specific threading model, their internal implementation could
be single-threaded or potentially maximize your multicore
architecture transparently!

Streams:Software Engineering Benefits

Java 8 Streams API
●Declarative— More concise and readable
●Composable— Greater flexibility
●Parallelizable— Better performance

Java 8 Streams API
●A short definition is “a sequence of elements from a source that
supports data processing operations.”
–Sequence of elements—
●Like a collection, a stream provides an interface to a
sequenced set of values of a specific element type.
●Because collections are data structures, they’re mostly about
storing and accessing elements with specific time/space
complexities (for example, an ArrayList vs. a LinkedList).
●But streams are about expressing computations such as filter,
sorted, and map .
●Collections are about data; streams are about
computations.

Java 8 Streams API
●A short definition is “a sequence of elements from a source that
supports data processing operations.”
–Source—
●Streams consume from a data-providing source such as
collections, arrays, or I/O resources.
●Note that generating a stream from an ordered collection
preserves the ordering.
●The elements of a stream coming from a list will have the
same order as the list.

Java 8 Streams API
●A short definition is “a sequence of elements from a source that
supports data processing operations.”
–Data processing operations—
●Streams support database-like operations and common
operations from functional programming languages to
manipulate data, such as filter, map, reduce, find, match,
sort, and so on.
●Stream operations can be executed either sequentially or
in parallel.

Java 8 Streams API
●A short definition is “a sequence of elements from a source that supports
data processing operations.”
–Pipelining—
●Many stream operations return a stream themselves, allowing
operations to be chained and form a larger pipeline.
●This enables certain optimizations , such as laziness and short-
circuiting.
●A pipeline of operations can be viewed as a database-like query
on the data source.
–Internal iteration—
●In contrast to collections, which are iterated explicitly using an
iterator, stream operations do the iteration behind the scenes.

Java 8 Streams API
The result is [chole,
bhature,chicken

Java 8 Streams API

Java 8 Streams API:Streams vs
Collection

Java 8 Streams API:Streams vs
Collection:Collection Iteration

Java 8 Streams API:Streams vs
Collection:Stream Iteration

Java 8 Streams API:Intermediate
Operations

Java 8 Streams API:Intermediate
Operations

Java 8 Streams API:Intermediate
Operations
●notice several optimizations due to the lazy nature of streams.
–First, despite the fact that many dishes have more than 300
calories, only the first three are selected! This is because of
the limit operation and a technique called short-circuiting.
–Second, despite the fact that filter and map are two separate
operations, they were merged into the same pass (we call
this technique loop fusion).

Java 8 Streams API:Intermediate
Operations

Java 8 Streams API:Terminal
Operations
●Terminal operations produce a result from a stream pipeline. A
result is any nonstream value such as a List, an Integer, or even
void.

Java 8 Streams API:Operations:distinct

Java 8 Streams API:Operations:limit

Java 8 Streams API:Operations:limit

Java 8 Streams API:Operations:map

Java 8 Streams API:Operations:map

Java 8 Streams API:Operations:map

Java 8 Streams API:Operations:flatmap

Java 8 Streams
API:Operations:matches

Java 8 Streams
API:Operations:matches

Optional vs Null

Java 8 Streams API:Operations:findFirst
vs FindAny
●The answer is parallelism. Finding the first element is more
constraining in parallel. If you don’t care about which element is
returned, use findAny because it’s less constraining when using
parallel streams.

Java 8 Streams API:Operations:reduce

Java 8 Streams API:Operations:reduce

Java 8 Streams API:Operations:reduce
vs step-by-step iterative summation
●The benefit of using reduce compared to the step-by-step iteration summation
is that the iteration is abstracted using internal iteration, which enables the
internal implementation to choose to perform the reduce operation in parallel.
–The iterative summation example involves shared updates to a sum
variable, which doesn’t parallelize gracefully. With needed synchronization,
the thread contention robs you of all the performance that parallelism was
supposed to give you!
–Parallelizing this computation requires a different approach: partition the
input, sum the partitions, and combine the sums.
–int sum = numbers.parallelStream().reduce(0, Integer::sum);
–But there’s a price to pay to execute this code in parallel, the lambda
passed to reduce can’t change state (for example, instance variables), and
the operation needs to be associative so it can be executed in any order.

Java 8 Streams API:Operations:max
and min

Java 8 Streams
API:Operations:Stateless vs Stateful
●Operations like map and filter take each element from the input
stream and produce zero or one result in the output stream.
These operations are thus in general stateless: they don’t have
an internal state (assuming the user-supplied lambda or method
reference has no internal mutable state).
●But operations like reduce, sum, and max need to have
internal state to accumulate the result. In this case the internal
state is small. The internal state is of bounded size no matter
how many elements are in the stream being processed.

Java 8 Streams
API:Operations:Stateless vs Stateful
●Some operations such as Sorted or Distinct seem at first to
behave like filter or map—all take a stream and produce
another stream (an intermediate operation), but there’s a crucial
difference.
–Both sorting and removing duplicates from a stream require
knowing the previous history to do their job.
–For example, sorting requires all the elements to be buffered
before a single item can be added to the output stream; the
storage requirement of the operation is unbounded.
–This can be problematic if the data stream is large or infinite.
These are stateful operations.

Java 8 Streams API:Operations:Details

Java 8 Streams API:Operations:Details

Java 8 Streams
API:Operations:Example

Java 8 Streams
API:Operations:Example

Java 8 Streams
API:Operations:Example

Java 8 Streams
API:Operations:Example

Java 8 Streams
API:Operations:Example

Java 8 Streams
API:Operations:Example

Java 8 Streams
API:Operations:Example

Java 8 Streams API:Primitive Stream
Behind the scenes
Each Integer needs
to be unboxed to a
primitive before performing
the summation.

Java 8 Streams API:Primitive Stream

Java 8 Streams API:Primitive
Stream:OptionalInt/Long/Double

Java 8 Streams API:Primitive
Stream:Numeric Ranges

Java 8 Streams API:Primitive
Stream:Pythagorean Triples

Java 8 Streams API:Building Streams

Java 8 Streams API:Building Streams

Java 8 Streams API:Infinite
Stream:Iterate

Java 8 Streams API:Infinite
Stream:Generate
Not good for parallel
Computation as it has
mutable state. The one with
iterate is immutable.

Java 8 Streams API:Collector

Java 8 Streams API:Collector

Java 8 Streams
API:Collector:Predefined
●Predefined collectors provide 3 main functionalities
–Reducing and summarizing stream elements to a single
value
–Grouping elements
–Partitioning elements

Java 8 Streams
API:Collector:Predefined:maxBy
Same implementation.
MaxBy,predefined, built on
top of generic reduce.

Java 8 Streams
API:Collector:Predefined:counting
Count calls counting,
counting built on top
of reduce

Java 8 Streams
API:Collector:Predefined:summingInt

Java 8 Streams
API:Collector:Predefined:summingInt

Java 8 Streams
API:Collector:Predefined:summingInt:tra
nsforming

Java 8 Streams
API:Collector:Predefined:summingInt:A
ggregation

Java 8 Streams
API:Collector:Predefined:summarizingIn
t

Java 8 Streams
API:Collector:Predefined:joining(uses
StringBuilder)

Java 8 Streams
API:Collector:Predefined:Collectors.red
ucing(generic factory)
●It takes three arguments:
–The first argument is the starting value of the reduction
operation and will also be the value returned in the case of a
stream with no elements, so clearly 0 is the appropriate
value in the case of a numeric sum.
–The second argument is the same function to transform a
dish into an int representing its calorie content.
–The third argument is a BinaryOperator that aggregates two
items into a single value of the same type. Here, it just sums
two ints.

Java 8 Streams API:Collector:Collect vs
Reduce
●This solution has two problems:
–a semantic one and a practical one. The semantic problem lies in the
fact that the reduce method is meant to combine two values and produce
a new one; it’s an immutable reduction. In contrast, the collect method is
designed to mutate a container to accumulate the result it’s supposed to
produce.
–using the reduce method with the wrong semantic is also the cause of a
practical problem: this reduction process can’t work in parallel because
theconcurrent modification of the same data structure operated by
multiple threads can corrupt the List itself.

Java 8 Streams API:Collector:Grouping

Java 8 Streams API:Collector:Grouping

Java 8 Streams
API:Collector:Grouping:Multilevel

Java 8 Streams
API:Collector:Grouping:Multilevel

Java 8 Streams
API:Collector:Grouping:collectingAndthe
n(Adapting to a different type)

Java 8 Streams
API:Collector:Grouping:collectingAndthen(Adapting to a different
type)

Java 8 Streams API:Collector:Grouping:reduction within a
reduction

Java 8 Streams API:Collector:Partitioning
Partitioning has the advantage of
keeping both lists of the stream
elements, for which the application
of the partitioning function returns
true or false.

Java 8 Streams API:Collector:Static factories

Java 8 Streams API:Collector:Static factories

Java 8 Streams API:Collector:Static factories

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Collector:Custom Collectors
●supplier() returns a function that creates an instance of
accumulator - mutable data structure that we will use to
accumulate input elements of type T
●accumulator() returns a function that will take accumulator and
one item of type T, mutating accumulator
●combiner() is used to join two accumulators together into one. It
is used when collector is executed in parallel, splitting input
Stream<T> and collecting parts independently first
●finisher() takes an accumulator A and turns it into a result value,
e.g. collection, of type R. All of this sounds quite abstract, so
let's do a simple example

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Collector:Custom Collectors
One possible optimization is to test
only if the candidate number is
divisible by prime numbers.The problem
with the predefined collectors is that
during the collecting process you don’t
have access to the partial result.

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Collector:Custom Collectors

Java 8 Streams API:Parallel Stream

Java 8 Streams API:Parallel Stream:parallel reduction

Java 8 Streams API:Parallel Stream

Java 8 Streams API:Parallel Stream

Java 8 Streams API:Parallel Stream
Not good for parallel
Computation as it has
mutable state.

Java 8 Streams API:Parallel Stream:Fork/Join

Java 8 Streams API:Parallel Stream:Fork/Join

Java 8 Streams API:Parallel Stream:Fork/Join

Java 8 Streams API:Parallel Stream:SplitIterator

Java 8 Streams API:Parallel Stream:SplitIterator:recursive splitting

Java 8 Streams API:Parallel Stream:SplitIterator:characteristics

Java 8 Streams API:Parallel Stream:SplitIterator:wordcount in
parallel

Java 8 Streams API:Parallel Stream:SplitIterator:wordcount in
parallel

Java 8 Streams API:Parallel Stream:SplitIterator:wordcount in
parallel

Java 8 Streams API:CompletableFuture

Java 8 Streams API:CompletableFuture

Java 8 Streams API:CompletableFuture

Java 8 Streams API:CompletableFuture:cascade

Java 8 Streams API:CompletableFuture:cascade

Java 8 Streams API:CompletableFuture:parallel

Java 8 Streams API:CompletableFuture:parallel

Java 8 Streams API:CompletableFuture:callback

Java 8 Streams API:CompletableFuture
Tags