SlideShare a Scribd company logo
1 of 75
Download to read offline
@mirocupak
Master class in modern
Java
Miro Cupak
Co-founder & VP Engineering, DNAstack
October 30, 2019
@mirocupak
Schedule
2
• 9:15am-1:15pm: Workshop, part #1.
• 1:15pm-2pm: Lunch break.
• 2pm-6pm: Workshop, part #2.
@mirocupak
Lessons
3
• Lesson 1: JShell.
• Lesson 2: Convenience factory methods for collections.
• Lesson 3: Improved try-with-resources.
• Lesson 4: Stream API enhancements.
• Lesson 5: Extensions to Optional.
• Lesson 6: CompletableFuture updates.
• Lesson 7: Reactive streams.
• Lesson 8: Process API.
• Lesson 9: HTTP/2 client.
• Lesson 10: Local variable type inference.
@mirocupak
Setup
4
• Prerequisites:
• JDK 13: https://jdk.java.net/13/
• Familiarity with Java 8.
• These slides.
Task 0.1
Verify you have JDK 13 with java -version.
@mirocupak 5
JShell
Lesson 1
@mirocupak
Lesson 1: JShell
6
Task 1.1
Start and exit JShell.
@mirocupak
Lesson 1: JShell
7
Task 1.2
Create a variable containing a string. Redefine the variable to contain an
integer.
@mirocupak
Lesson 1: JShell
8
Task 1.3
Call a method that might throw a (checked) exception. How is it handled?
What happens when an exception is thrown? How is a location in JShell
referenced in a stacktrace?
@mirocupak
Lesson 1: JShell
9
Task 1.4
Create a simple method and call it. Create a class containing a method
and call it.
@mirocupak
Lesson 1: JShell
10
Task 1.5
Modify your method to call another method that you haven’t implemented
yet. What happens?
@mirocupak
Lesson 1: JShell
11
Task 1.6
Show the current time.
@mirocupak
Lesson 1: JShell
12
Task 1.7
Find what keyboard shortcuts JShell supports. Try them out. How do you
view Javadoc?
@mirocupak
Lesson 1: JShell
13
Task 1.8
What are the possible arguments for the /list and /edit commands?
@mirocupak
Lesson 1: JShell
14
Task 1.9
Save your current snippets, restart JShell, and load the snippets you
saved. Save all the commands and snippets for later use.
@mirocupak
Lesson 1: JShell
15
Task 1.10
Explore the /env command. Load an external library and use it from
JShell.
@mirocupak
Lesson 1: JShell
16
Task 1.11
Set the feedback mode and editor to whatever you’re comfortable with.
@mirocupak
Lesson 1: JShell
17
Task 1.12
Use JShell to explore its own API. Use the API to process a snippet of your
choice and read the results.
@mirocupak
Lesson 1: JShell
18
• Useful tool for whenever you need to try out something small quickly.
• Not a debugging tool.
• Prefer IDEs for any larger tasks.
• Use /help for more information about commands.
• Configure your own editor.
• More info: JEP 222: jshell: The Java Shell (Read-Eval-Print Loop).
@mirocupak 19
Convenience factory
methods for collections
Lesson 2
@mirocupak
Lesson 2: Convenience factory methods for collections
20
Task 2.1
How would you create an immutable list in Java 8? What are the problems
with this approach? Are there any alternatives?
@mirocupak
Lesson 2: Convenience factory methods for collections
21
Task 2.2
What is the type of the return value of the of method?
@mirocupak
Lesson 2: Convenience factory methods for collections
22
Task 2.3
What’s the API for creating immutable collections for Set and Map? Does it
differ from List?
@mirocupak
Lesson 2: Convenience factory methods for collections
23
Task 2.4
What’s the API for creating immutable copies of collections for a Map? How
does it differ from the respective API in List and Set?
@mirocupak
Lesson 2: Convenience factory methods for collections
24
Task 2.5
How do you get the output of a stream into an immutable collection?
@mirocupak
Lesson 2: Convenience factory methods for collections
25
Task 2.6
What’s the most concise way of converting a collection into an array?
@mirocupak
Lesson 2: Convenience factory methods for collections
26
• Obtain immutable collections via of/ofEntries methods.
• Create immutable copies of collections via copyOf (Java 10).
• Static import java.util.Map.entry.
• Less verbose, no static initializer blocks.
• Don’t use Arrays.asList or Stream.of as shortcuts for creating collections.
• Don’t use external libraries if you only need immutable collections (Guava).
• No need to worry about leaving references to underlying collections.
• Thread-safe and can be shared freely (no need for defensive copies).
• Good performance.
• Don’t create mutable collections unless necessary.
• More info: JEP 269: Convenience Factory Methods for Collections.
@mirocupak 27
Improved try-with-resources
Lesson 3
@mirocupak
Lesson 3: Improved try-with-resources
28
Task 3.1
Read a file from disk to standard output (copy to standard output). Make
sure you clean up the resources as needed.
@mirocupak
Lesson 3: Improved try-with-resources
29
Task 3.2
Refactor your previous example to take advantage of effectively final
variables.
@mirocupak
Lesson 3: Improved try-with-resources
30
Task 3.3
Can we make the code even simpler?
Hint: Check out the InputStream API for useful methods.
@mirocupak
Lesson 3: Improved try-with-resources
31
• Always prefer try-with-resources, don’t use try-finally and definitely don’t use finalizers to close resources.
• Be aware of convenience methods, such as InputStream.transferTo.
• Don’t create unnecessary helper objects.
• More info: JEP 213: Milling Project Coin.
@mirocupak 32
Stream API enhancements
Lesson 4
@mirocupak
Lesson 4: Stream API enhancements
33
Task 4.1
Modify the stream below to only print the numbers <5 (>5).
IntStream.range(0,10).forEach(System.out::println)
@mirocupak
Lesson 4: Stream API enhancements
34
Task 4.2
Demonstrate a difference between filter and takeWhile
(dropWhile).
Hint: Print even numbers <100.
@mirocupak
Lesson 4: Stream API enhancements
35
Task 4.3
Improve the code from the previous task.
@mirocupak
Lesson 4: Stream API enhancements
36
Task 4.4
Come up with a scenario where ofNullable helps.
@mirocupak
Lesson 4: Stream API enhancements
37
Task 4.5
Suppose we have the following list of numbers:
List.of(2, 3, 4, 7, 9, 11)
Count the numbers >5 by parity.
Hint: filtering.
@mirocupak
Lesson 4: Stream API enhancements
38
Task 4.6
Compute average of elements in a stream.
Hint: teeing.
@mirocupak
Lesson 4: Stream API enhancements
39
Task 4.6
Explore how the pattern matching API plays nicely with streams.
Hint: Use Matcher to obtain all results of a match.
Task 4.7
Explore how the date-time API plays nicely with streams.
Hint: Use LocalDate to obtain list of dates between now and Christmas.
@mirocupak
Lesson 4: Stream API enhancements
40
• Be aware of new stream methods: takeWhile, dropWhile, iterate.
• Familiarize yourself with various collectors available out of the box.
• Prefer collecting into immutable collections using toUnmodifiableList, toUnmodifiableSet,
toUnmodifiableMap.
• Check for convenience stream methods before converting to streams manually (e.g. LocalDate,
Matcher).
• Avoid unnecessary null checks with ofNullable.
• Streams are suitable for more use cases now, but not all use cases.
• Don’t overuse streams as they can make code hard to read and difficult to maintain.
@mirocupak 41
Extensions to Optional
Lesson 5
@mirocupak
Lesson 5: Extensions to Optional
42
Task 5.1
Given an Optional, print its value if the value is present, otherwise print
“empty”.
@mirocupak
Lesson 5: Extensions to Optional
43
Task 5.2
What other methods in the Optional API are similar to or?
@mirocupak
Lesson 5: Extensions to Optional
44
Task 5.3
Another 2 methods in the same family were added in Java 10. Can you
find them?
@mirocupak
Lesson 5: Extensions to Optional
45
Task 5.4
Filter out empty values from a given collection of Optionals, e.g.:
List.of(Optional.of(1), Optional.empty(),
Optional.of(2))
Hint: flatMap.
@mirocupak
Lesson 5: Extensions to Optional
46
• Use ifPresentOrElse instead of if-isPresent construct.
• or provides a clean fluent way of chaining behaviour on Optionals.
• Be aware of orElse* methods, e.g. the new orElseThrow (Java 10).
• Use stream to take advantage of the lazy nature of streams and handle streams of Optionals.
• Remember that isPresent is rarely the answer.
@mirocupak 47
CompletableFuture updates
Lesson 6
@mirocupak
Lesson 6: CompletableFuture updates
48
Task 6.1
completeOnTimeout is great for completing a future normally based on
a timeout. How do I complete a future exceptionally based on a timeout?
@mirocupak
Lesson 6: CompletableFuture updates
49
Task 6.2
Inspect the contract of the copy method. Demonstrate the one-way
synchronization it provides.
@mirocupak
Lesson 6: CompletableFuture updates
50
Task 6.3
Take some time to explore other new additions to the
CompletableFuture API we haven’t talked about.
@mirocupak
Lesson 6: CompletableFuture updates
51
• With Java 9+, you can complete CompletableFutures normally and exceptionally based on a timeout
(completeOnTimeout, orTimeout).
• copy provides an easy method for building asynchronous APIs.
• It’s usually a good idea to make copies before exposing CompletableFuture in APIs.
• Be aware of the various utility methods in the CompletableFuture API.
• More info: JEP 266: More Concurrency Updates.
@mirocupak 52
Reactive streams
Lesson 7
@mirocupak
Lesson 7: Reactive streams
53
Task 7.1
Implement a subscriber echoing messages from the publisher.
Hint: Request new message in onSubscribe and onNext.
@mirocupak
Lesson 7: Reactive streams
54
Task 7.2
What happens if we request 2 messages in onNext every time? How
about Long.MAX_VALUE?
@mirocupak
Lesson 7: Reactive streams
55
Task 7.3
What happens if we request 0 messages in onNext every time?
@mirocupak
Lesson 7: Reactive streams
56
Task 7.4
What happens if we subscribe a subscriber twice to a publisher?
@mirocupak
Lesson 7: Reactive streams
57
Task 7.5
What happens if we subscribe a subscriber to 2 publishers?
@mirocupak
Lesson 7: Reactive streams
58
Task 7.6
What happens if we submit a message after closing the publisher?
@mirocupak
Lesson 7: Reactive streams
59
• The right approach for asynchronous stream processing with nonblocking back pressure.
• Don’t implement yourself, use a library.
• More info: JEP 266: More Concurrency Updates.
@mirocupak 60
Process API
Lesson 8
@mirocupak
Lesson 8: Process API
61
Task 8.1
Launch an external process from Java. What are the problems with this
API?
@mirocupak
Lesson 8: Process API
62
Task 8.2
List all the commands running in your OS visible to you.
Hint: allProcesses.
@mirocupak
Lesson 8: Process API
63
Task 8.3
Launch an external process that runs for 3 seconds. Print the PID of the
(now dead) process as soon as it finishes.
Hint: sleep 3.
@mirocupak
Lesson 8: Process API
64
Task 8.4
List your currently running Java processes with jps. Use grep to find
JShell in the list.
Hint: startPipeline.
@mirocupak
Lesson 8: Process API
65
• ProcessHandle is a clean way of obtaining information about processes.
• Don’t implement yourself. Don’t use MXBeans or OS utilities.
• Take advantage of convenience methods: pid, info, command…
• Trigger actions on process termination via onExit.
• Connect ProcessBuilder with ProcessHandle via toHandle.
• Create pipelines via ProcessBuilder.startPipeline.
• More info: JEP 102: Process API Updates.
@mirocupak 66
HTTP/2 client
Lesson 9
@mirocupak
Lesson 9: HTTP/2 client
67
Task 9.1
Execute an HTTP request against a server the old-fashioned way
(HttpURLConnection API). Read the status code as well as the body of
the response.
@mirocupak
Lesson 9: HTTP/2 client
68
Task 9.2
Use the new HTTP/2 client API to execute a request against a server. Read
the response.
@mirocupak
Lesson 9: HTTP/2 client
69
Task 9.3
Use the new HTTP/2 client API to execute a request against a server
asynchronously. Read the response.
@mirocupak
Lesson 10: HTTP/2 client
70
Task 9.4
Explore the rest of the HTTP/2 client API.
@mirocupak
Lesson 9: HTTP/2 client
71
• Clean separation: HttpClient, HttpRequest, HttpResponse.
• HttpURLConnection is not pleasant to use.
• Avoid APIs with side effects.
• The new client API is versatile, flexible and clean.
• Prefer functionality in the JDK to external libraries.
• More info: JEP 110: HTTP 2 Client.
@mirocupak 72
Local variable type
inference
Lesson 10
@mirocupak
Lesson 10: Local variable type inference
73
• Does not replace static typing.
• Generally good - reduces boilerplate, improves readability, and helps with maintenance and refactoring.
• Use for local variables with initializers (especially constructors) and for loops.
• Use for complex types when breaking chained or nested expressions with local variables.
• Can’t use for declarations without explicit initialization, null or array initializers, compound declarations,
method signatures, class fields, catch formals, lambdas or method references.
• Consider whether to use when the generated type is not obvious.
• Primitive types might surprise you, be careful (e.g. byte, short, long all inferred as int).
• Code to the interface pattern does not work, but that’s kind of OK.
• Be very careful about combining with <> and generic methods (e.g. var list = new ArrayList<>()).
• Works with non-denotable types (e.g. intersection types), but be careful!
• Capture variables are projected to supertypes that do not mention capture variables.
@mirocupak
Lesson 10: Local variable type inference
74
• Probably not the best idea to use with anonymous classes.
• Use carefully chosen and expressive variable names.
• Don’t use var as names of variables, methods, enums (even if it works).
• Don’t use Hungarian notation.
• Don’t rely on IDEs.
• Minimize the scope of local variables.
• Declare variable when it’s first used.
• Declaration not containing an initializer (i.e. you can’t use var) often indicates the scope is not minimal.
• Prefer for loops to while loops.
• Keep methods small and focused.More info: JEP 286: Local-Variable Type Inference.
@mirocupak
Questions?
75

More Related Content

What's hot

Php com con-2011
Php com con-2011Php com con-2011
Php com con-2011LB Denker
 
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Igalia
 
CPAN Exporter modules for Perl 5
CPAN Exporter modules for Perl 5CPAN Exporter modules for Perl 5
CPAN Exporter modules for Perl 5neilbowers
 
Take your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to ModernizationTake your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to ModernizationOrtus Solutions, Corp
 
Queick: A Simple Job Queue System for Python
Queick: A Simple Job Queue System for PythonQueick: A Simple Job Queue System for Python
Queick: A Simple Job Queue System for PythonRyota Suenaga
 
Finding CPAN adoption candidates
Finding CPAN adoption candidatesFinding CPAN adoption candidates
Finding CPAN adoption candidatesneilbowers
 
Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)Fabio Tiriticco
 
Reviewing CPAN modules
Reviewing CPAN modulesReviewing CPAN modules
Reviewing CPAN modulesneilbowers
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
java8-patterns
java8-patternsjava8-patterns
java8-patternsJustin Lin
 
Java EE 7 meets Java 8
Java EE 7 meets Java 8Java EE 7 meets Java 8
Java EE 7 meets Java 8Roberto Cortez
 
Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData Oleg Tsal-Tsalko
 
Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Scott Keck-Warren
 

What's hot (19)

Php com con-2011
Php com con-2011Php com con-2011
Php com con-2011
 
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
 
CPAN Exporter modules for Perl 5
CPAN Exporter modules for Perl 5CPAN Exporter modules for Perl 5
CPAN Exporter modules for Perl 5
 
Take your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to ModernizationTake your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to Modernization
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
 
Taverna as a service
Taverna as a serviceTaverna as a service
Taverna as a service
 
Queick: A Simple Job Queue System for Python
Queick: A Simple Job Queue System for PythonQueick: A Simple Job Queue System for Python
Queick: A Simple Job Queue System for Python
 
Finding CPAN adoption candidates
Finding CPAN adoption candidatesFinding CPAN adoption candidates
Finding CPAN adoption candidates
 
Maven
MavenMaven
Maven
 
Perl-Critic
Perl-CriticPerl-Critic
Perl-Critic
 
Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)
 
Reviewing CPAN modules
Reviewing CPAN modulesReviewing CPAN modules
Reviewing CPAN modules
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
java8-patterns
java8-patternsjava8-patterns
java8-patterns
 
Java EE 7 meets Java 8
Java EE 7 meets Java 8Java EE 7 meets Java 8
Java EE 7 meets Java 8
 
Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData
 
Intro to CakePHP
Intro to CakePHPIntro to CakePHP
Intro to CakePHP
 
Perl in Teh Cloud
Perl in Teh CloudPerl in Teh Cloud
Perl in Teh Cloud
 
Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021
 

Similar to Master class in modern Java

Deep Dive in Java 9+
Deep Dive in Java 9+Deep Dive in Java 9+
Deep Dive in Java 9+Miro Cupak
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Voxxed Athens 2018 - Clean Code with Java9+
Voxxed Athens 2018 - Clean Code with Java9+Voxxed Athens 2018 - Clean Code with Java9+
Voxxed Athens 2018 - Clean Code with Java9+Voxxed Athens
 
Writing clean code with Java 9+
Writing clean code with Java 9+Writing clean code with Java 9+
Writing clean code with Java 9+Miro Cupak
 
JRuby 6 Years in Production
JRuby 6 Years in ProductionJRuby 6 Years in Production
JRuby 6 Years in ProductionMark Menard
 
A Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated RefactoringA Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated RefactoringRaffi Khatchadourian
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designMiro Cupak
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designMiro Cupak
 
SBW 2016: MultiQC Workshop
SBW 2016: MultiQC WorkshopSBW 2016: MultiQC Workshop
SBW 2016: MultiQC WorkshopPhil Ewels
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Abdul Hannan
 
Ansible top 10 - 2018
Ansible top 10 -  2018Ansible top 10 -  2018
Ansible top 10 - 2018Viresh Doshi
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designMiro Cupak
 
SciPipe - A light-weight workflow library inspired by flow-based programming
SciPipe - A light-weight workflow library inspired by flow-based programmingSciPipe - A light-weight workflow library inspired by flow-based programming
SciPipe - A light-weight workflow library inspired by flow-based programmingSamuel Lampa
 
SOA with PHP and Symfony
SOA with PHP and SymfonySOA with PHP and Symfony
SOA with PHP and SymfonyMichalSchroeder
 
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Molieremfrancis
 
Pipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei MccollumPipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei MccollumLorelei McCollum
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9Gal Marder
 
Applying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScriptApplying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScriptJulian Gamble
 

Similar to Master class in modern Java (20)

Deep Dive in Java 9+
Deep Dive in Java 9+Deep Dive in Java 9+
Deep Dive in Java 9+
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Voxxed Athens 2018 - Clean Code with Java9+
Voxxed Athens 2018 - Clean Code with Java9+Voxxed Athens 2018 - Clean Code with Java9+
Voxxed Athens 2018 - Clean Code with Java9+
 
Writing clean code with Java 9+
Writing clean code with Java 9+Writing clean code with Java 9+
Writing clean code with Java 9+
 
JRuby 6 Years in Production
JRuby 6 Years in ProductionJRuby 6 Years in Production
JRuby 6 Years in Production
 
A Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated RefactoringA Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated Refactoring
 
XPDays-2018
XPDays-2018XPDays-2018
XPDays-2018
 
Come si applica l'OCP
Come si applica l'OCPCome si applica l'OCP
Come si applica l'OCP
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API design
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API design
 
SBW 2016: MultiQC Workshop
SBW 2016: MultiQC WorkshopSBW 2016: MultiQC Workshop
SBW 2016: MultiQC Workshop
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
 
Ansible top 10 - 2018
Ansible top 10 -  2018Ansible top 10 -  2018
Ansible top 10 - 2018
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API design
 
SciPipe - A light-weight workflow library inspired by flow-based programming
SciPipe - A light-weight workflow library inspired by flow-based programmingSciPipe - A light-weight workflow library inspired by flow-based programming
SciPipe - A light-weight workflow library inspired by flow-based programming
 
SOA with PHP and Symfony
SOA with PHP and SymfonySOA with PHP and Symfony
SOA with PHP and Symfony
 
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
 
Pipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei MccollumPipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei Mccollum
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Applying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScriptApplying the paradigms of core.async in Clojure and ClojureScript
Applying the paradigms of core.async in Clojure and ClojureScript
 

More from Miro Cupak

Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14Miro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Exploring the last year of Java
Exploring the last year of JavaExploring the last year of Java
Exploring the last year of JavaMiro Cupak
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Miro Cupak
 
The Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API designThe Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API designMiro Cupak
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Miro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern JavaMiro Cupak
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designMiro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern JavaMiro Cupak
 
Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)Miro Cupak
 
Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11Miro Cupak
 
Exploring what's new in Java in 2018
Exploring what's new in Java in 2018Exploring what's new in Java in 2018
Exploring what's new in Java in 2018Miro Cupak
 
Reactive programming in Java
Reactive programming in JavaReactive programming in Java
Reactive programming in JavaMiro Cupak
 
Exploring reactive programming with Java
Exploring reactive programming with JavaExploring reactive programming with Java
Exploring reactive programming with JavaMiro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Writing clean code with Java in 2018
Writing clean code with Java in 2018Writing clean code with Java in 2018
Writing clean code with Java in 2018Miro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 

More from Miro Cupak (20)

Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Exploring the last year of Java
Exploring the last year of JavaExploring the last year of Java
Exploring the last year of Java
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?
 
The Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API designThe Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API design
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern Java
 
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API designThe good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API design
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern Java
 
Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)
 
Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11
 
Exploring what's new in Java in 2018
Exploring what's new in Java in 2018Exploring what's new in Java in 2018
Exploring what's new in Java in 2018
 
Reactive programming in Java
Reactive programming in JavaReactive programming in Java
Reactive programming in Java
 
Exploring reactive programming with Java
Exploring reactive programming with JavaExploring reactive programming with Java
Exploring reactive programming with Java
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Writing clean code with Java in 2018
Writing clean code with Java in 2018Writing clean code with Java in 2018
Writing clean code with Java in 2018
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 

Recently uploaded

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 

Master class in modern Java

  • 1. @mirocupak Master class in modern Java Miro Cupak Co-founder & VP Engineering, DNAstack October 30, 2019
  • 2. @mirocupak Schedule 2 • 9:15am-1:15pm: Workshop, part #1. • 1:15pm-2pm: Lunch break. • 2pm-6pm: Workshop, part #2.
  • 3. @mirocupak Lessons 3 • Lesson 1: JShell. • Lesson 2: Convenience factory methods for collections. • Lesson 3: Improved try-with-resources. • Lesson 4: Stream API enhancements. • Lesson 5: Extensions to Optional. • Lesson 6: CompletableFuture updates. • Lesson 7: Reactive streams. • Lesson 8: Process API. • Lesson 9: HTTP/2 client. • Lesson 10: Local variable type inference.
  • 4. @mirocupak Setup 4 • Prerequisites: • JDK 13: https://jdk.java.net/13/ • Familiarity with Java 8. • These slides. Task 0.1 Verify you have JDK 13 with java -version.
  • 6. @mirocupak Lesson 1: JShell 6 Task 1.1 Start and exit JShell.
  • 7. @mirocupak Lesson 1: JShell 7 Task 1.2 Create a variable containing a string. Redefine the variable to contain an integer.
  • 8. @mirocupak Lesson 1: JShell 8 Task 1.3 Call a method that might throw a (checked) exception. How is it handled? What happens when an exception is thrown? How is a location in JShell referenced in a stacktrace?
  • 9. @mirocupak Lesson 1: JShell 9 Task 1.4 Create a simple method and call it. Create a class containing a method and call it.
  • 10. @mirocupak Lesson 1: JShell 10 Task 1.5 Modify your method to call another method that you haven’t implemented yet. What happens?
  • 11. @mirocupak Lesson 1: JShell 11 Task 1.6 Show the current time.
  • 12. @mirocupak Lesson 1: JShell 12 Task 1.7 Find what keyboard shortcuts JShell supports. Try them out. How do you view Javadoc?
  • 13. @mirocupak Lesson 1: JShell 13 Task 1.8 What are the possible arguments for the /list and /edit commands?
  • 14. @mirocupak Lesson 1: JShell 14 Task 1.9 Save your current snippets, restart JShell, and load the snippets you saved. Save all the commands and snippets for later use.
  • 15. @mirocupak Lesson 1: JShell 15 Task 1.10 Explore the /env command. Load an external library and use it from JShell.
  • 16. @mirocupak Lesson 1: JShell 16 Task 1.11 Set the feedback mode and editor to whatever you’re comfortable with.
  • 17. @mirocupak Lesson 1: JShell 17 Task 1.12 Use JShell to explore its own API. Use the API to process a snippet of your choice and read the results.
  • 18. @mirocupak Lesson 1: JShell 18 • Useful tool for whenever you need to try out something small quickly. • Not a debugging tool. • Prefer IDEs for any larger tasks. • Use /help for more information about commands. • Configure your own editor. • More info: JEP 222: jshell: The Java Shell (Read-Eval-Print Loop).
  • 19. @mirocupak 19 Convenience factory methods for collections Lesson 2
  • 20. @mirocupak Lesson 2: Convenience factory methods for collections 20 Task 2.1 How would you create an immutable list in Java 8? What are the problems with this approach? Are there any alternatives?
  • 21. @mirocupak Lesson 2: Convenience factory methods for collections 21 Task 2.2 What is the type of the return value of the of method?
  • 22. @mirocupak Lesson 2: Convenience factory methods for collections 22 Task 2.3 What’s the API for creating immutable collections for Set and Map? Does it differ from List?
  • 23. @mirocupak Lesson 2: Convenience factory methods for collections 23 Task 2.4 What’s the API for creating immutable copies of collections for a Map? How does it differ from the respective API in List and Set?
  • 24. @mirocupak Lesson 2: Convenience factory methods for collections 24 Task 2.5 How do you get the output of a stream into an immutable collection?
  • 25. @mirocupak Lesson 2: Convenience factory methods for collections 25 Task 2.6 What’s the most concise way of converting a collection into an array?
  • 26. @mirocupak Lesson 2: Convenience factory methods for collections 26 • Obtain immutable collections via of/ofEntries methods. • Create immutable copies of collections via copyOf (Java 10). • Static import java.util.Map.entry. • Less verbose, no static initializer blocks. • Don’t use Arrays.asList or Stream.of as shortcuts for creating collections. • Don’t use external libraries if you only need immutable collections (Guava). • No need to worry about leaving references to underlying collections. • Thread-safe and can be shared freely (no need for defensive copies). • Good performance. • Don’t create mutable collections unless necessary. • More info: JEP 269: Convenience Factory Methods for Collections.
  • 28. @mirocupak Lesson 3: Improved try-with-resources 28 Task 3.1 Read a file from disk to standard output (copy to standard output). Make sure you clean up the resources as needed.
  • 29. @mirocupak Lesson 3: Improved try-with-resources 29 Task 3.2 Refactor your previous example to take advantage of effectively final variables.
  • 30. @mirocupak Lesson 3: Improved try-with-resources 30 Task 3.3 Can we make the code even simpler? Hint: Check out the InputStream API for useful methods.
  • 31. @mirocupak Lesson 3: Improved try-with-resources 31 • Always prefer try-with-resources, don’t use try-finally and definitely don’t use finalizers to close resources. • Be aware of convenience methods, such as InputStream.transferTo. • Don’t create unnecessary helper objects. • More info: JEP 213: Milling Project Coin.
  • 32. @mirocupak 32 Stream API enhancements Lesson 4
  • 33. @mirocupak Lesson 4: Stream API enhancements 33 Task 4.1 Modify the stream below to only print the numbers <5 (>5). IntStream.range(0,10).forEach(System.out::println)
  • 34. @mirocupak Lesson 4: Stream API enhancements 34 Task 4.2 Demonstrate a difference between filter and takeWhile (dropWhile). Hint: Print even numbers <100.
  • 35. @mirocupak Lesson 4: Stream API enhancements 35 Task 4.3 Improve the code from the previous task.
  • 36. @mirocupak Lesson 4: Stream API enhancements 36 Task 4.4 Come up with a scenario where ofNullable helps.
  • 37. @mirocupak Lesson 4: Stream API enhancements 37 Task 4.5 Suppose we have the following list of numbers: List.of(2, 3, 4, 7, 9, 11) Count the numbers >5 by parity. Hint: filtering.
  • 38. @mirocupak Lesson 4: Stream API enhancements 38 Task 4.6 Compute average of elements in a stream. Hint: teeing.
  • 39. @mirocupak Lesson 4: Stream API enhancements 39 Task 4.6 Explore how the pattern matching API plays nicely with streams. Hint: Use Matcher to obtain all results of a match. Task 4.7 Explore how the date-time API plays nicely with streams. Hint: Use LocalDate to obtain list of dates between now and Christmas.
  • 40. @mirocupak Lesson 4: Stream API enhancements 40 • Be aware of new stream methods: takeWhile, dropWhile, iterate. • Familiarize yourself with various collectors available out of the box. • Prefer collecting into immutable collections using toUnmodifiableList, toUnmodifiableSet, toUnmodifiableMap. • Check for convenience stream methods before converting to streams manually (e.g. LocalDate, Matcher). • Avoid unnecessary null checks with ofNullable. • Streams are suitable for more use cases now, but not all use cases. • Don’t overuse streams as they can make code hard to read and difficult to maintain.
  • 41. @mirocupak 41 Extensions to Optional Lesson 5
  • 42. @mirocupak Lesson 5: Extensions to Optional 42 Task 5.1 Given an Optional, print its value if the value is present, otherwise print “empty”.
  • 43. @mirocupak Lesson 5: Extensions to Optional 43 Task 5.2 What other methods in the Optional API are similar to or?
  • 44. @mirocupak Lesson 5: Extensions to Optional 44 Task 5.3 Another 2 methods in the same family were added in Java 10. Can you find them?
  • 45. @mirocupak Lesson 5: Extensions to Optional 45 Task 5.4 Filter out empty values from a given collection of Optionals, e.g.: List.of(Optional.of(1), Optional.empty(), Optional.of(2)) Hint: flatMap.
  • 46. @mirocupak Lesson 5: Extensions to Optional 46 • Use ifPresentOrElse instead of if-isPresent construct. • or provides a clean fluent way of chaining behaviour on Optionals. • Be aware of orElse* methods, e.g. the new orElseThrow (Java 10). • Use stream to take advantage of the lazy nature of streams and handle streams of Optionals. • Remember that isPresent is rarely the answer.
  • 48. @mirocupak Lesson 6: CompletableFuture updates 48 Task 6.1 completeOnTimeout is great for completing a future normally based on a timeout. How do I complete a future exceptionally based on a timeout?
  • 49. @mirocupak Lesson 6: CompletableFuture updates 49 Task 6.2 Inspect the contract of the copy method. Demonstrate the one-way synchronization it provides.
  • 50. @mirocupak Lesson 6: CompletableFuture updates 50 Task 6.3 Take some time to explore other new additions to the CompletableFuture API we haven’t talked about.
  • 51. @mirocupak Lesson 6: CompletableFuture updates 51 • With Java 9+, you can complete CompletableFutures normally and exceptionally based on a timeout (completeOnTimeout, orTimeout). • copy provides an easy method for building asynchronous APIs. • It’s usually a good idea to make copies before exposing CompletableFuture in APIs. • Be aware of the various utility methods in the CompletableFuture API. • More info: JEP 266: More Concurrency Updates.
  • 53. @mirocupak Lesson 7: Reactive streams 53 Task 7.1 Implement a subscriber echoing messages from the publisher. Hint: Request new message in onSubscribe and onNext.
  • 54. @mirocupak Lesson 7: Reactive streams 54 Task 7.2 What happens if we request 2 messages in onNext every time? How about Long.MAX_VALUE?
  • 55. @mirocupak Lesson 7: Reactive streams 55 Task 7.3 What happens if we request 0 messages in onNext every time?
  • 56. @mirocupak Lesson 7: Reactive streams 56 Task 7.4 What happens if we subscribe a subscriber twice to a publisher?
  • 57. @mirocupak Lesson 7: Reactive streams 57 Task 7.5 What happens if we subscribe a subscriber to 2 publishers?
  • 58. @mirocupak Lesson 7: Reactive streams 58 Task 7.6 What happens if we submit a message after closing the publisher?
  • 59. @mirocupak Lesson 7: Reactive streams 59 • The right approach for asynchronous stream processing with nonblocking back pressure. • Don’t implement yourself, use a library. • More info: JEP 266: More Concurrency Updates.
  • 61. @mirocupak Lesson 8: Process API 61 Task 8.1 Launch an external process from Java. What are the problems with this API?
  • 62. @mirocupak Lesson 8: Process API 62 Task 8.2 List all the commands running in your OS visible to you. Hint: allProcesses.
  • 63. @mirocupak Lesson 8: Process API 63 Task 8.3 Launch an external process that runs for 3 seconds. Print the PID of the (now dead) process as soon as it finishes. Hint: sleep 3.
  • 64. @mirocupak Lesson 8: Process API 64 Task 8.4 List your currently running Java processes with jps. Use grep to find JShell in the list. Hint: startPipeline.
  • 65. @mirocupak Lesson 8: Process API 65 • ProcessHandle is a clean way of obtaining information about processes. • Don’t implement yourself. Don’t use MXBeans or OS utilities. • Take advantage of convenience methods: pid, info, command… • Trigger actions on process termination via onExit. • Connect ProcessBuilder with ProcessHandle via toHandle. • Create pipelines via ProcessBuilder.startPipeline. • More info: JEP 102: Process API Updates.
  • 67. @mirocupak Lesson 9: HTTP/2 client 67 Task 9.1 Execute an HTTP request against a server the old-fashioned way (HttpURLConnection API). Read the status code as well as the body of the response.
  • 68. @mirocupak Lesson 9: HTTP/2 client 68 Task 9.2 Use the new HTTP/2 client API to execute a request against a server. Read the response.
  • 69. @mirocupak Lesson 9: HTTP/2 client 69 Task 9.3 Use the new HTTP/2 client API to execute a request against a server asynchronously. Read the response.
  • 70. @mirocupak Lesson 10: HTTP/2 client 70 Task 9.4 Explore the rest of the HTTP/2 client API.
  • 71. @mirocupak Lesson 9: HTTP/2 client 71 • Clean separation: HttpClient, HttpRequest, HttpResponse. • HttpURLConnection is not pleasant to use. • Avoid APIs with side effects. • The new client API is versatile, flexible and clean. • Prefer functionality in the JDK to external libraries. • More info: JEP 110: HTTP 2 Client.
  • 72. @mirocupak 72 Local variable type inference Lesson 10
  • 73. @mirocupak Lesson 10: Local variable type inference 73 • Does not replace static typing. • Generally good - reduces boilerplate, improves readability, and helps with maintenance and refactoring. • Use for local variables with initializers (especially constructors) and for loops. • Use for complex types when breaking chained or nested expressions with local variables. • Can’t use for declarations without explicit initialization, null or array initializers, compound declarations, method signatures, class fields, catch formals, lambdas or method references. • Consider whether to use when the generated type is not obvious. • Primitive types might surprise you, be careful (e.g. byte, short, long all inferred as int). • Code to the interface pattern does not work, but that’s kind of OK. • Be very careful about combining with <> and generic methods (e.g. var list = new ArrayList<>()). • Works with non-denotable types (e.g. intersection types), but be careful! • Capture variables are projected to supertypes that do not mention capture variables.
  • 74. @mirocupak Lesson 10: Local variable type inference 74 • Probably not the best idea to use with anonymous classes. • Use carefully chosen and expressive variable names. • Don’t use var as names of variables, methods, enums (even if it works). • Don’t use Hungarian notation. • Don’t rely on IDEs. • Minimize the scope of local variables. • Declare variable when it’s first used. • Declaration not containing an initializer (i.e. you can’t use var) often indicates the scope is not minimal. • Prefer for loops to while loops. • Keep methods small and focused.More info: JEP 286: Local-Variable Type Inference.