SlideShare une entreprise Scribd logo
1  sur  42
1
Java 7 & 8
Yannick De Turck
Ken Coenen
2
Java 7 & 8
 18h15 – Java 7 (Ken)
 18h45 – Q&A
 19h – Java 8 (Yannick)
 19h30 – Q&A
 19h45 – Exercises
 20h30 – Solutions
 21h - Finish
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
4
Java 7: String in switch-statement
5
Java 7: Automatic resource management
 Try-with-resources statement
- Resources are automatically closed
 New AutoCloseable interface available to implement for your own
classes
6
Java 7: Automatic resource management
7
Java 7: Diamond syntax
 Type Inference for Generic Instance Creation
 No longer required to repeat the type when instantiation
8
Java 7: Better Exception handling with multi-catch
 No longer one Exception per catch limit
9
Java 7: Better Exception handling with multi-catch
 Precise rethrowing
10
Java 7: Literal enhancements
 Prefix binary literals with 0b or 0B
 Use underscores in your number literals to increase readability
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
- ...
12
Java 7: New IO API
13
Java 7: New IO API
14
Java 7: New IO API
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
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
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
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
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!));
20
Java 8: Lambda Expressions
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?
22
Java 8: Extension Methods
 Override method and pick the right implementation
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);
24
Java 8: Functional Interfaces
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
26
Java 8: Method and Constructor References
27
Java 8: Method and Constructor References
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
29
Java 8: Streams and Bulk Data Operations for
Collections
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)
 ...
31
Java 8: Streams and Bulk Data Operations for
Collections
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!)
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!
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
- …
35
Java 8: New Date & Time API
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)
37
Java 8: New Default API for Base64 Encoding
38
Java 8: Improvements for Annotations
 Annotations in Java 8 are repeatable
 @Repeatable
39
Java 8: Improvements for Annotations
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
41
Sources
 https://github.com/yannickdeturck/workshop-java-7-8
(or shorter url: http://tinyurl.com/lzy56ng)
 Java 8 Cheatsheet: http://www.java8.org
42
Questions ?

Contenu connexe

Tendances

Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
 

Tendances (20)

Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
What's new in Java 11
What's new in Java 11What's new in Java 11
What's new in Java 11
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Fork Join
Fork JoinFork Join
Fork Join
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
 
RxJava@DAUG
RxJava@DAUGRxJava@DAUG
RxJava@DAUG
 
JVM
JVMJVM
JVM
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
rx-java-presentation
rx-java-presentationrx-java-presentation
rx-java-presentation
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Reactive by example - at Reversim Summit 2015
Reactive by example - at Reversim Summit 2015Reactive by example - at Reversim Summit 2015
Reactive by example - at Reversim Summit 2015
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 

En vedette (8)

CV Sutthiphorn Manowong
CV Sutthiphorn ManowongCV Sutthiphorn Manowong
CV Sutthiphorn Manowong
 
As modificações na Linguagem: Java 7 e Java 8
As modificações na Linguagem: Java 7 e Java 8As modificações na Linguagem: Java 7 e Java 8
As modificações na Linguagem: Java 7 e Java 8
 
APLICAÇÃO JAVA DE CADASTRO DE NOTA FISCAL USANDO BANCO MYSQL
APLICAÇÃO JAVA DE CADASTRO DE NOTA FISCAL USANDO BANCO MYSQLAPLICAÇÃO JAVA DE CADASTRO DE NOTA FISCAL USANDO BANCO MYSQL
APLICAÇÃO JAVA DE CADASTRO DE NOTA FISCAL USANDO BANCO MYSQL
 
Curso pvt 1_gas_uerj
Curso pvt 1_gas_uerjCurso pvt 1_gas_uerj
Curso pvt 1_gas_uerj
 
Física de gases
Física de gasesFísica de gases
Física de gases
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
Estudo dos gases slides
Estudo dos gases   slidesEstudo dos gases   slides
Estudo dos gases slides
 
Lei geral dos gases
Lei geral dos gasesLei geral dos gases
Lei geral dos gases
 

Similaire à Java 7 & 8 - A&BP CC

Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Nayden Gochev
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
Nayden Gochev
 

Similaire à Java 7 & 8 - A&BP CC (20)

Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Panama.pdf
Panama.pdfPanama.pdf
Panama.pdf
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 
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 8
Java 8Java 8
Java 8
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
JavaOne 2011 Recap
JavaOne 2011 RecapJavaOne 2011 Recap
JavaOne 2011 Recap
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
 
Java SE 8 & EE 7 Launch
Java SE 8 & EE 7 LaunchJava SE 8 & EE 7 Launch
Java SE 8 & EE 7 Launch
 
IBM InterConnect: Java vs JavaScript for Enterprise WebApps
IBM InterConnect: Java vs JavaScript for Enterprise WebAppsIBM InterConnect: Java vs JavaScript for Enterprise WebApps
IBM InterConnect: Java vs JavaScript for Enterprise WebApps
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_en
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
The features of java 11 vs. java 12
The features of  java 11 vs. java 12The features of  java 11 vs. java 12
The features of java 11 vs. java 12
 

Plus de JWORKS powered by Ordina

Plus de JWORKS powered by Ordina (20)

Introduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & WebIntroduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & Web
 
Lagom in Practice
Lagom in PracticeLagom in Practice
Lagom in Practice
 
Netflix OSS and HATEOAS deployed on production - JavaLand
Netflix OSS and HATEOAS deployed on production - JavaLandNetflix OSS and HATEOAS deployed on production - JavaLand
Netflix OSS and HATEOAS deployed on production - JavaLand
 
Cc internet of things @ Thomas More
Cc internet of things @ Thomas MoreCc internet of things @ Thomas More
Cc internet of things @ Thomas More
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
An introduction to Cloud Foundry
An introduction to Cloud FoundryAn introduction to Cloud Foundry
An introduction to Cloud Foundry
 
Cc internet of things LoRa and IoT - Innovation Enablers
Cc internet of things   LoRa and IoT - Innovation Enablers Cc internet of things   LoRa and IoT - Innovation Enablers
Cc internet of things LoRa and IoT - Innovation Enablers
 
Mongodb @ vrt
Mongodb @ vrtMongodb @ vrt
Mongodb @ vrt
 
Mongo db intro.pptx
Mongo db intro.pptxMongo db intro.pptx
Mongo db intro.pptx
 
Big data document and graph d bs - couch-db and orientdb
Big data  document and graph d bs - couch-db and orientdbBig data  document and graph d bs - couch-db and orientdb
Big data document and graph d bs - couch-db and orientdb
 
Big data key-value and column stores redis - cassandra
Big data  key-value and column stores redis - cassandraBig data  key-value and column stores redis - cassandra
Big data key-value and column stores redis - cassandra
 
Hadoop bootcamp getting started
Hadoop bootcamp getting startedHadoop bootcamp getting started
Hadoop bootcamp getting started
 
Big data elasticsearch practical
Big data  elasticsearch practicalBig data  elasticsearch practical
Big data elasticsearch practical
 
Intro to cassandra
Intro to cassandraIntro to cassandra
Intro to cassandra
 
Android wear - CC Mobile
Android wear - CC MobileAndroid wear - CC Mobile
Android wear - CC Mobile
 
Clean Code - A&BP CC
Clean Code - A&BP CCClean Code - A&BP CC
Clean Code - A&BP CC
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Integration testing - A&BP CC
Integration testing - A&BP CCIntegration testing - A&BP CC
Integration testing - A&BP CC
 
Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 

Dernier

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 

Java 7 & 8 - A&BP CC

  • 1. 1 Java 7 & 8 Yannick De Turck Ken Coenen
  • 2. 2 Java 7 & 8  18h15 – Java 7 (Ken)  18h45 – Q&A  19h – Java 8 (Yannick)  19h30 – Q&A  19h45 – Exercises  20h30 – Solutions  21h - Finish
  • 3. 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
  • 4. 4 Java 7: String in switch-statement
  • 5. 5 Java 7: Automatic resource management  Try-with-resources statement - Resources are automatically closed  New AutoCloseable interface available to implement for your own classes
  • 6. 6 Java 7: Automatic resource management
  • 7. 7 Java 7: Diamond syntax  Type Inference for Generic Instance Creation  No longer required to repeat the type when instantiation
  • 8. 8 Java 7: Better Exception handling with multi-catch  No longer one Exception per catch limit
  • 9. 9 Java 7: Better Exception handling with multi-catch  Precise rethrowing
  • 10. 10 Java 7: Literal enhancements  Prefix binary literals with 0b or 0B  Use underscores in your number literals to increase readability
  • 11. 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 - ...
  • 12. 12 Java 7: New IO API
  • 13. 13 Java 7: New IO API
  • 14. 14 Java 7: New IO API
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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!));
  • 20. 20 Java 8: Lambda Expressions
  • 21. 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?
  • 22. 22 Java 8: Extension Methods  Override method and pick the right implementation
  • 23. 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);
  • 24. 24 Java 8: Functional Interfaces
  • 25. 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
  • 26. 26 Java 8: Method and Constructor References
  • 27. 27 Java 8: Method and Constructor References
  • 28. 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
  • 29. 29 Java 8: Streams and Bulk Data Operations for Collections
  • 30. 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)  ...
  • 31. 31 Java 8: Streams and Bulk Data Operations for Collections
  • 32. 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!)
  • 33. 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!
  • 34. 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 - …
  • 35. 35 Java 8: New Date & Time API
  • 36. 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)
  • 37. 37 Java 8: New Default API for Base64 Encoding
  • 38. 38 Java 8: Improvements for Annotations  Annotations in Java 8 are repeatable  @Repeatable
  • 39. 39 Java 8: Improvements for Annotations
  • 40. 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
  • 41. 41 Sources  https://github.com/yannickdeturck/workshop-java-7-8 (or shorter url: http://tinyurl.com/lzy56ng)  Java 8 Cheatsheet: http://www.java8.org

Notes de l'éditeur

  1. Welkom, onszelf voorstellen, ABP, structuur avond, volgende workshops, kleine inleiding waarom deze workshop interessant zou moeten zijn -> self assessment, enterprise omgeving Java 7
  2. String in switch is faster than if … equals else … (Java compiler generates generally more efficient bytecode). Uses the String.equals method.
  3. The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. The resource is closed automatically in a finally block that’s added at compile time (http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html)
  4. Eg. The classes InputStream and OutputStream, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. The resource is closed automatically in a finally block that’s added at compile time (http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html)
  5. You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context (so no-go for anonymous inner classes!). Note that omitting the diamond operator doesn’t have the same effect. You’ll get an unchecked conversion warning, because the instantiation refers to the raw type instead of the generic class.
  6. Pipeline is used to group Exceptions that should be handled the same way. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
  7. Note that NoSuchFieldException extends ReflectiveOperationException. The compiler is smart enough to determine that only NoSuchFieldException can be thrown so it’s not mandatory to add the ReflectiveOperationException to the method signature. Advantage can be that if you have multiple implementations of a ReflectiveOperationException, you do not need to list them all in the catch declaration. This again saves time.
  8. Integral types (byte, short, int, and long) can also be expressed using the binary number system. Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This can improve the readability of your code.
  9. Lots of interesting stuff in there, be sure to have a look at that package! A zip file system provider is also available in JDK 7 (check out http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html for more information). Stream: Element not cached, can’t move back and forth without first buffering Buffer: Data is read into a buffer to be processed later, can move back and forth. More flexible during processing but the buffer might not contain all data necessary to process it. Blocking: read(), write() -> Thread blocked until data is read of fully written Non-blocking: Thread gets what’s available (possibly nothing) or thread writes but doesn’t wait until it’s fully written. -> Single thread can manage multiple inputs and outputs Files: Static methods that operate on files, directories, or other types of files. FileSystem: Provides an interface to a file system and is the factory (getInstance()) for objects to access files and other objects in the file system. Path: Offers more functionalities than File, File now has a toPath()-method. Similar methods compared to File but methods now throw Exceptions (example: delete()) More properties available for consulting (DOS and POSIX), returns null if it isn’t supported on the system.
  10. Listens to events that take place in the directory that’s being watched. watchKey.take(): Retrieves and removes next watch key, waiting if none are yet present. Returns: the next watch key watchKey.reset(): Resets this watch key. If this watch key has been cancelled or this watch key is already in the ready state then invoking this method has no effect. Otherwise if there are pending events for the object then this watch key is immediately re-queued to the watch service. If there are no pending events then the watch key is put into the ready state and will remain in that state until an event is detected or the watch key is cancelled. Returns: true if the watch key is valid and has been reset, and false if the watch key could not be reset because it is no longer valid
  11. Crawls through a directory, skips, svn-folders and prints out the directories and files found.
  12. A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same (or related) type, until these become simple enough to be solved directly. Tasks are divided into smaller parts to be processed, results are combined into one
  13. ForBlur.java is an example of a picture being blurred by going through it’s pixels
  14. The heap is partitioned into a set of equal-sized heap regions, each a contiguous range of virtual memory. G1 performs a concurrent global marking phase to determine the liveness of objects throughout the heap. After the mark phase completes, G1 knows which regions are mostly empty. It collects in these regions first, which usually yields a large amount of free space. This is why this method of garbage collection is called Garbage-First. G1 compacts sufficiently to completely avoid the use of fine-grained free lists for allocation, and instead relies on regions. Also, G1 offers more predictable garbage collection pauses than the CMS collector, and allows users to specify desired pause targets.
  15. Hot topic op Devoxx. Java releases komen sneller en sneller uit dus belangrijk om bij te blijven
  16. Functionali programming: Immutable data. State is handled via parameter passing, avoids side effects. Split up the problem in a chain of functions that need to be executed where each function takes input and returns a result. Think about what transformations need to happen. Recursion is used more often. Functions are first class citizens. Data flow. OOP: Mutable. State changes. Write the exact steps in detail to solve a particular problem. Control flow. Note that when using brackets in a lambda expression ‘;’s are mandatory at the end of the line!! Java compiler compiles lambda expressions and convert them into private methods of the class.
  17. Note how the type of param can be left out and parentheses aren’t necessary if there’s only one param.
  18. Specify implementations in your interface! This also allows existing interfaces to be extended with new functionalities without breaking backwards compatibility. Not limited to only one default method.
  19. A warning is given by your IDE when more than one method is specified inside a FunctionalInterface. Trying to compile the project will also fail. When omitting the @FunctionalInterface annotation, the project will compile and a lambda expression can be used to implement calculate(int a). Some of the functional interfaces might be familiar if you’ve used Guava such as Predicate. Supplier: provides objects
  20. Anonymous inner class vs lambda. Notice how you are actually passing a function as a parameter. Assigning the lambda to a variable is usually skipped.
  21. :: syntax was introduced in Java 8 to reference methods
  22. These method references are possible since they accept a param of F and have a result of T. forEach accepts a Consumer<T> where T is the type of an element of the Collection.
  23. Picking the right constructor method is context dependent, in this case since BookFactory defines a method with 2 params, the second constructor of Book is used.
  24. Why stream? Not a data structure that stores elements, it conveys elements from a source Does not modify its source (functional in nature), instead it produces a new stream Laziness-seeking, opportunity for optimalisation (example: find first 3 strings with even number of characters, doesn’t need to traverse through all elements) Collections have an finite size where as streams do not Each element of a stream is only visited once thus a new stream must be generated to revisit the same elements
  25. putIfAbsent: If the specified key doesn’t have a value (null) assign the specified value to it. Returns null if the value was assigned, otherwise return the value. (note: already existed in ConcurrentMap in Java <8, now available to all Maps) forEach: execute the consumer for each element computeIfPresent: If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value computeIfAbsent: If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null getOrDefault: Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key
  26. Human time: separate fields for years, months, days, hours, minutes, seconds, and, in line with the current fashion, nanoseconds. Machine time: number of milliseconds since epoch, which you may obtain, for example, via System.currentTimeMillis() call. This does not replace the existing Data API, it simply offers a better solution for doing calculations with dates.
  27. sun.misc.BASE64Encoder wasn’t even documented…
  28. Basic vs Url: Url-friendly encoding Notice output no longer than 76 chars and ends with carriage return followed by a line feed
  29. Note that the container annotation is still used but this time the Java compiler is responsible for wrapping the repeating annotations into a container annotation.
  30. Note that the container annotation is still used but this time the Java compiler is responsible for wrapping the repeating annotations into a container annotation.