Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
77 views

School of Java 2019 - Java 8

The document discusses Java 8 features including lambda expressions, default and static methods in interfaces, and improvements to the time, collection, and concurrency APIs. It provides an overview of functional programming concepts like pure functions, side effects, and currying. Lambdas are introduced as Java's way for functional programming, allowing functions to be passed as arguments. Best practices for lambdas like omitting types and avoiding lambdas for multi-line computations are covered.

Uploaded by

Alina Ane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

School of Java 2019 - Java 8

The document discusses Java 8 features including lambda expressions, default and static methods in interfaces, and improvements to the time, collection, and concurrency APIs. It provides an overview of functional programming concepts like pure functions, side effects, and currying. Lambdas are introduced as Java's way for functional programming, allowing functions to be passed as arguments. Best practices for lambdas like omitting types and avoiding lambdas for multi-line computations are covered.

Uploaded by

Alina Ane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

1

JAVA 8 INTRO & LAMBDAS


SCHOOL OF JAVA , MARCH 2019
AGENDA

 OVERVIEW 2
 ABOUT FUNCTIONAL PROGRAMMING
 LAMBDAS

2
OVERVIEW

SOME JAVA 8 FEATURES:


• Default and static methods in interfaces
• Time API 3
• Collection API improvements
• Concurrency API improvements
• Lambda Expressions and Functional Interfaces
• Optional
• Stream API

3
OVERVIEW
DEFAULT AND STATIC METHODS IN INTERFACES

A default method:
4
public interface IsWarmBlooded { • is a method defined within an interface with the default
public default double getTemperature() { keyword in which a method body is provided
return 10.0;
}
}
• helps with code development and backwards
compatibility

4
OVERVIEW
DEFAULT AND STATIC METHODS IN INTERFACES

A static method:
5
public interface Hop {
static int getJumpHeight() { • is not inherited in any classes that implement the
return 8; interface
}
}
• to reference the static method, a reference to the name
of the interface must be used

5
OVERVIEW
TIME API
What changed Old way Java 8 way
Importing import java.util.*; import java .time.*;
Creating an object Date d = new Date(); LocalDate d = LocalDate.now();
with the current date
Creating an object Date d = new Date(); LocalDateTime dt = LocalDateTime.now();
with the current date and time 6
Creating an object Calendar c = Calendar.getInstance(); LocalDate jan = LocalDate.of(2015, Month.JANUARY, 1);
representing January 1, 2015 c.set(2015, Calendar. JANUARY, 1);
Date jan = c.getTime();

Creating January 1, 2015 Calendar c = Calendar.getInstance(); LocalDate jan = LocalDate.of(2015, 1, 1)


without the constant c.set(2015, 0, 1);
Date jan = c.getTime();

6
OVERVIEW
COLLECTION API IMPROVEMENTS

Class/interface New methods


Map getOrDefault, forEach, compute, computeIfAbsent, computeIfPresent,
merge, putIfAbsent, remove(key, value), replace, replaceAll
Iterable forEach, spliterator
7
Iterator forEachRemaining
Collection removeIf, stream, parallelStream
List replaceAll, sort
BitSet stream
Comparator reversed, thenComparing, thenComparingInt, thenComparingDouble,
thenComparingLong, comparingInt, naturalOrder, nullsFirst, nullsLast,
reverseOrder

7
OVERVIEW
CONCURRENCY API IMPROVEMENTS
• Atomic
The java.util.concurrent.atomic package offers several numeric classes, such as AtomicInteger and AtomicLong that
support atomic operation on single variables. They were updated to support new methods: getAndUpdate, updateAndGet,
getAndAccumulate, accumulateAndGet.

• Adders and accumulators


8
The Java API recommends using the new classes LongAdder, LongAccumulator, Double-Adder, and DoubleAccumulator
instead of the Atomic classes equivalent when multiple threads update frequently but read less frequently (for example, in the
context of statistics). These classes are designed to grow dynamically to reduce thread contention.

• ConcurrentHashMap
The ConcurrentHashMap class was introduced to provide a more modern HashMap, which is concurrent friendly.
ConcurrentHashMap allows concurrent add and updates that lock only certain parts of the internal data structure. Thus, read and
write operations have improved performance compared to the synchronized Hashtable alternative.

8
AGENDA

 OVERVIEW 9
 ABOUT FUNCTIONAL PROGRAMMING
 LAMBDA EXPRESSIONS

9
ABOUT FUNCTIONAL PROGRAMMING
What?
Functional programming is a way of writing code more declaratively. You specify what you want
to do rather than dealing with the state of objects. You focus more on expressions than loops.

Side effects 10
A function has a side effect if it does something other than simply return a result, e.g.
modifying a variable, setting a field on an object, throwing/halting an exception.

Pure functions
A function with no side effects honors immutability and does not change its input
or anything in its reach and does not depend on anything that changes is a pure
function.

10
ABOUT FUNCTIONAL PROGRAMMING

High-order functions

• function that takes other functions as


arguments or returns a function as result. 11
• instead of solely relying on objects and
classes to promote reuse, with higher-order
functions we can easily reuse small, focused,
cohesive, and well-written functions.

11
ABOUT FUNCTIONAL PROGRAMMING

Currying is the process of taking a function that accepts N arguments and turning it into a
chained series of N functions each taking 1 argument.

12

12
AGENDA

 OVERVIEW 13
 ABOUT FUNCTIONAL PROGRAMMING
 LAMBDA EXPRESSIONS(LAMBDAS)

13
LAMBDAS
Lambdas are Java’s new way for functional programming

Collections.sort(list, new Comparator<String>() {


Before Java 8 @Override
public int compare(String o1, String o2) {
14 return Integer.compare(o1.length(), o2.length());
}
});

Java 8 with lambda Collections.sort(list, (o1, o2) -> Integer.compare(o1.length(), o2.length()));

14
LAMBDAS

• Note that the types of the lambda (Comparator<String>), of its parameters (o1 and o2, both String),
and of its return value (int) are not present in the code.
15

• The compiler deduces these types from context, using a process known as type inference. In some
cases, the compiler won’t be able to determine the types, and you’ll have to specify them.

15
LAMBDAS

16

16
LAMBDAS

17

17
LAMBDAS
EFFECTIVELY FINAL

Is there a problem?

void print(int x) {
A variable or parameter whose value is never 18
changed after it is initialized is effectively final. x = 99;

Consumer<Integer> myConsumer = y ->


A lambda expression can only access local
{
variables and parameters of the enclosing block System.out.println("x = " + x);
that are final or effectively final. System.out.println("y = " + y);
};

myConsumer.accept(x);

}}

18
LAMBDAS

BEST PRACTICES

19
• Omit the types of all lambda parameters unless their presence makes your program clearer.

• Because lambdas lack names and documentation; if a computation isn’t self-explanatory, or


exceeds a few lines, don’t put it in a lambda.

19
LAMBDAS
METHOD REFERENCE

20

20
ANSWERS
ConcurrentHashMap

• Before Java 8, each ConcurrentHashMap had a “concurrency level” which was fixed at construction
time. For compatibility reasons, there is still a constructor accepting such a level though not using it
in the original way. The map was split into as many segments, as its concurrency level, each of
them having its own lock, so in theory, there could21 be up to concurrency level concurrent updates, if
they all happened to target different segments, which depends on the hashing.

• In Java 8, each hash bucket can get updated individually, so as long as there are no hash collisions,
there can be as many concurrent updates as its current capacity. This is in line with the new
features like the compute methods which guaranty atomic updates, hence, locking of at least the
hash bucket which gets updated. In the best case, they lock indeed only that single bucket.

21
ANSWERS

ConcurrentHashMap vs synchronized HashMap

• ConcurrentHashMap is thread safe without synchronizing


22 the whole map. Reads can happen
very fast while write is done with a lock. Both are synchronized version of HashMap,
with difference in their core functionality and their internal structure.

22
ANSWERS

Effectively final in lambdas

You may be asking yourself why local variables have these restrictions. First, there’s a key difference
in how instance and local variables are implemented behind the scenes. Instance variables are stored
23
on the heap, whereas local variables live on the stack.

If a lambda could access the local variable directly and the lambda were used in a thread, then the
thread using the lambda could try to access the variable after the thread that allocated the variable had
deallocated it. Hence, Java implements access to a free local variable as access to a copy of it rather
than access to the original variable.
This makes no difference if the local variable is assigned to only once hence the restriction. Second,
this restriction also discourages typical imperative programming patterns that mutate an outer variable.

23

You might also like