Java 7 & 8

42
1 Java 7 & 8 Yannick De Turck Ken Coenen

description

In this workshop we would like to take a closer look at the new features of Java 7 and Java 8. Java 7 has brought a couple of language enhancements to assist developers in their daily programming tasks and starting from Java 8 we finally have the opportunity to include a functional programming touch to Java thanks to Lambdas! Lambdas allow us to specify closures to create clean and brief solutions for which we would otherwise be obligated to write down a lot of boilerplate code. For example in order to sort a List of Strings based on their length we can now write the following code: Collections.sort(list, (s1, s2) -> s1.length() - s2.length()); Besides lambdas, Java 8 also comes with extension methods, allowing us to write interfaces containing implemented methods, streams and bulk data operations, granting us the opportunity to chain operations on collections to obtain a filtered or transformed set of the elements in our collection, and the possibility to pass functions as parameters. These features alone will have a major impact on the way how Java APIs can be written. There's also a brand new Date and Time API inspired on the popular JodaTime API and a couple of other language enhancements to aid Java developers in writing solutions in a more elegant way. Be sure to follow this workshop to stay up to date with the latest evolutions of the Java programming language. Java 8 is definitely an update of the programming language which you don't want to miss out on!

Transcript of Java 7 & 8

Page 1: Java 7 & 8

1

Java 7 & 8

Yannick De Turck

Ken Coenen

Page 2: Java 7 & 8

2

Java 7 & 8

18h15 – Java 7 (Ken)

18h45 – Q&A

19h – Java 8 (Yannick)

19h30 – Q&A

19h45 – Exercises

20h30 – Solutions

21h - Finish

Page 3: Java 7 & 8

3

Java 7 (July 28th 2011)

String in switch-statement

Automatic resource management

Diamond syntax

Better Exception handling with multi-catch

Literal enhancements

New IO API

Fork Join Framework

JVM enhancements

Page 4: Java 7 & 8

4

Java 7: String in switch-statement

Page 5: Java 7 & 8

5

Java 7: Automatic resource management

Try-with-resources statement

- Resources are automatically closed

New AutoCloseable interface available to implement for your own

classes

Page 6: Java 7 & 8

6

Java 7: Automatic resource management

Page 7: Java 7 & 8

7

Java 7: Diamond syntax

Type Inference for Generic Instance Creation

No longer required to repeat the type when instantiation

Page 8: Java 7 & 8

8

Java 7: Better Exception handling with multi-catch

No longer one Exception per catch limit

Page 9: Java 7 & 8

9

Java 7: Better Exception handling with multi-catch

Precise rethrowing

Page 10: Java 7 & 8

10

Java 7: Literal enhancements

Prefix binary literals with 0b or 0B

Use underscores in your number literals to increase readability

Page 11: Java 7 & 8

11

Java 7: New IO API

A whole new package: java.nio

Non-blocking IO

Buffer oriented instead of Stream oriented

New classes to improve working with files

- Files

- Path

- FileSystem

- WatchService

- FileVisitor

- ...

Page 12: Java 7 & 8

12

Java 7: New IO API

Page 13: Java 7 & 8

13

Java 7: New IO API

Page 14: Java 7 & 8

14

Java 7: New IO API

Page 15: Java 7 & 8

15

Java 7: Fork Join Framework

Parallel programming

- Divide a process into smaller tasks via recursion which are handled by a processor

- Combine the processed pieces into one result

- Divide & conquer

Page 16: Java 7 & 8

16

Java 7: Fork Join Framework

Extend RecursiveAction or RecursiveTasks

if (my portion of the work is small enough) {

do the work directly

} else {

split my work into two pieces

invoke the two pieces and wait for the results

}

Practical example: ForkBlur.java

Page 17: Java 7 & 8

17

Java 7: JVM enhancements

Support for dynamically typed languages

- Introduction of invokedynamic

A new bytecode instruction on the JVM for method invocation

http://niklasschlimm.blogspot.be/2012/02/java-7-complete-invokedynamic-example.html

- Performance improvements for other languages living in the JVM such as Ruby, Groovy, …

Garbage-First Collector (or G1 collector)

- Will eventually replace the Concurrent Mark-Sweep Collector (CMS)

- Advantages: works with regions, more predictable

Page 18: Java 7 & 8

18

Java 8 (March 18th 2014)

Lambda Expressions

Extension Methods

Functional Interfaces

Method and Constructor References

Streams and Bulk Data Operations for Collections

Removal of PermGen

New Date & Time API

New Default API for Base 64 Encoding

Improvements for Annotations

General Performance Improvements

Page 19: Java 7 & 8

19

Java 8: Lambda Expressions

Allows writing code in a functional style

Passing behaviour to a method

Prior to Java 8: Anonymous Inner Class

Java 8: Lambda Expressions

Gets rid of boiler plate code

More readable and clear code

Type of param may be specified but isn’t obligated(params) -> expression

() -> System.out.println(“Hello world!”);

myButton.addActionListener

() -> {

doThis();

doThat();

}((e) -> println(“Clicked!));

Page 20: Java 7 & 8

20

Java 8: Lambda Expressions

Page 21: Java 7 & 8

21

Java 8: Extension Methods

Add non-abstract method implementations to interfaces using the ‘default’

keyword

But what happens if default methods collide when using multiple interfaces?

Page 22: Java 7 & 8

22

Java 8: Extension Methods

Override method and pick the right implementation

Page 23: Java 7 & 8

23

Java 8: Functional Interfaces

@FunctionalInterface

An interface with exactly one abstract method

Lambda expression is applicable as implementation

Build-in Functional Interfaces (java.util.function)

- Predicate<T>: boolean test(T t);

- Function<T>: R apply(T t);

- Supplier<T>: T get();

- Consumer<T>: void accept(T t);

- Comparator<T>: int compare(T o1, T o2);

Page 24: Java 7 & 8

24

Java 8: Functional Interfaces

Page 25: Java 7 & 8

25

Java 8: Method and Constructor References

Pass references of methods or constructors using the :: keyword

Useful in combination with the Predicate class

Bit shorter compared to lambdas

ContainingClass::staticMethodName

ContainingObject::instanceMethodName

ContainingType::methodName

ClassName::new

String::valueOf

s::toString

String::toString

String::new

Page 26: Java 7 & 8

26

Java 8: Method and Constructor References

Page 27: Java 7 & 8

27

Java 8: Method and Constructor References

Page 28: Java 7 & 8

28

Java 8: Streams and Bulk Data Operations for Collections

java.util.Stream

A sequence of elements on which one or more operations can be performed

Intermediate vs terminal operation

- Intermediate: returns the stream itself in order to be able to chain operations

- Terminal: returns a result of a certain type

Streams are created on a source such as a java.util.Collection

Can be executed sequential or parallel

Parallel utilises Fork-Join

- Watch out with long-running tasks! Blocks threads in the pool

Page 29: Java 7 & 8

29

Java 8: Streams and Bulk Data Operations for Collections

Page 30: Java 7 & 8

30

Java 8: Streams and Bulk Data Operations for Collections

Maps

- Don’t support streams :-(

- … But they now support various new and useful methods for executing common tasks!

V putIfAbsent(K key, V value)

void forEach(BiConsumer<? super K,? super V> action)

V computeIfPresent(K key, BiFunction<? super K,? super V,?

extends V> remappingFunction)

V computeIfAbsent(K key, Function<? super K,? extends

V> mappingFunction)

V getOrDefault(Object key, V defaultValue)

...

Page 31: Java 7 & 8

31

Java 8: Streams and Bulk Data Operations for Collections

Page 32: Java 7 & 8

32

Java 8: Streams and Bulk Data Operations for Collections

Optional<T>

- May or may not contain a non-null value

- Avoid working with null (no NPEs!)

Page 33: Java 7 & 8

33

Java 8: Removal of PermGen

PermGen memory space completely removed

- PermSize and MaxPermSize JVM arguments are ignored and a warning

gets displayed

Gets replaced by Metaspace

- XX:MaxMetaspaceSize flag, default is unlimited

- System memory is the limit instead of the fixed size at startup of PermGen

- Metaspace will dynamically resize depending on demand at runtime

Note that this does not magically fixes your memory leaks!

Page 34: Java 7 & 8

34

Java 8: New Date & Time API

Inspired by Joda Time

- Human time vs computer time (aka millis since epoch)

Offers a solution to the sometimes cumbersome way of calculating dates and time

Interesting new classes:

- Clock

- ZoneId

- LocalDate (date without timezone)

- LocalTime (time without timezone)

- LocalDateTime (datetime without timezone)

- DateTimeFormatter

- …

Page 35: Java 7 & 8

35

Java 8: New Date & Time API

Page 36: Java 7 & 8

36

Java 8: New Default API for Base64 Encoding

More extensive API than the 1.6+ Base64 API (sun.misc.BASE64Encoder)

3 encoders and decoders

- Basic (For regular encoding)

- URL (Encoded String needs to be used in file or url)

- MIME (MIME friendly encoding)

Page 37: Java 7 & 8

37

Java 8: New Default API for Base64 Encoding

Page 38: Java 7 & 8

38

Java 8: Improvements for Annotations

Annotations in Java 8 are repeatable

@Repeatable

Page 39: Java 7 & 8

39

Java 8: Improvements for Annotations

Page 40: Java 7 & 8

40

Java 8: General Performance Improvements

Performs a bit faster compared to Java 7

Great performance improvement when making use of parallelism

Example with Arrays.sort

Page 41: Java 7 & 8

41

Sources

https://github.com/yannickdeturck/workshop-java-7-8(or shorter url: http://tinyurl.com/lzy56ng)

Java 8 Cheatsheet: http://www.java8.org

Page 42: Java 7 & 8

42

Questions ?