Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Deep Dive in Java 9+

176 views

Published on

Deep Dive in Java 9+ workshop at VoxxedDays Athens 2018.

Having arrived over 3 years after Java 8, Java 9 is a big release full of exciting new features, closely followed by the smaller Java 10 under the new rapid release schedule. This workshop is a deep dive into everything application developers need to know about making their code better with modern JDKs.

You will learn how to use JShell, Java’s Read-Eval-Print-Loop implementation, and use it to explore various new APIs, language enhancements, as well as other features of JDK 9 and 10. We will talk about best practices and patterns for using these features in the context of modern applications with special emphasis on producing clean code.

This is a very hands-on session providing you with the opportunity to truly learn modern Java by solving a series of tasks covering many of its exciting features.

Published in: Software
  • Be the first to comment

Deep Dive in Java 9+

  1. 1. @mirocupak Miro Cupak VP Engineering, DNAstack 31/05/2018 Deep Dive in Java 9+
  2. 2. @mirocupak Lessons !2 • Lesson 1: JShell. • Lesson 2: Convenience factory methods for collections. • Lesson 3: Improved try-with-resources. • Lesson 4: Private methods in interfaces. • Lesson 5: Stream API enhancements. • Lesson 6: Extensions to Optional. • Lesson 7: CompletableFuture updates. • Lesson 8: StackWalker. • Lesson 9: Process API. • Lesson 10: HTTP/2 client. • Lesson 11: Type inference. • Lesson 12: Modularity.
  3. 3. @mirocupak Organization !3 • 12 independent lessons • lesson structure: • theory • demo • exercises • solutions • best practices • (optional) reading • environment: JShell
  4. 4. @mirocupak Setup !4 • Prerequisites: • JDK 10: http://www.oracle.com/technetwork/java/javase/downloads/ jdk10-downloads-4416644.html • Familiarity with Java 8. • These slides: https://www.slideshare.net/MiroCupak/presentations Task 0.1 Verify you have JDK 10 with java -version.
  5. 5. @mirocupak !5 JShell Lesson 1
  6. 6. @mirocupak Lesson 1: JShell !6 Task 1.1 Start and exit JShell.
  7. 7. @mirocupak Lesson 1: JShell !7 Task 1.2 Create a variable containing a string. Redefine the variable to contain an integer.
  8. 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. 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. 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. 11. @mirocupak Lesson 1: JShell !11 Task 1.6 Show the current time.
  12. 12. @mirocupak Lesson 1: JShell !12 Task 1.7 Find what keyboard shortcuts JShell supports. Try them out. How do you view Javadoc?
  13. 13. @mirocupak Lesson 1: JShell !13 Task 1.8 What are the possible arguments for the /list and /edit commands?
  14. 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. 15. @mirocupak Lesson 1: JShell !15 Task 1.10 Explore the /env command. Load an external library and use it from JShell. Unload it when done.
  16. 16. @mirocupak Lesson 1: JShell !16 Task 1.11 Set the feedback mode and editor to whatever you’re comfortable with.
  17. 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. 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. 19. @mirocupak !19 Convenience factory methods for collections Lesson 2
  20. 20. @mirocupak Lesson 2: Convenience factory methods for collections !20 Task 2.1 How would you create an immutable set in Java 8? What are the problems with this approach? Are there any alternatives?
  21. 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. 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. 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. 24. @mirocupak !24 • 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). Lesson 2: Convenience factory methods for collections
  25. 25. @mirocupak !25 • Good performance. • Don’t create mutable collections unless necessary. • More info: JEP 269: Convenience Factory Methods for Collections. Lesson 2: Convenience factory methods for collections
  26. 26. @mirocupak !26 Improved try-with-resources Lesson 3
  27. 27. @mirocupak Lesson 3: Improved try-with- resources !27 Task 3.1 Read a file from disk to standard output (copy to standard output). Make sure you clean up the resources as needed.
  28. 28. @mirocupak Lesson 3: Improved try-with- resources !28 Task 3.2 Refactor your previous example to take advantage of effectively final variables.
  29. 29. @mirocupak Lesson 3: Improved try-with- resources !29 Task 3.3 Can we make the code even simpler? Hint: Check out the InputStream API for useful methods.
  30. 30. @mirocupak !30 • 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. Lesson 3: Improved try-with- resources
  31. 31. @mirocupak !31 Private methods in interfaces Lesson 4
  32. 32. @mirocupak Lesson 4: Private methods in interfaces !32 Task 4.1 Create an interface containing a private method. Provide an implementation of this interface. Demonstrate the benefit of the private method.
  33. 33. @mirocupak !33 • Default methods, like all other methods, should be short. • DRY. • Use private methods to keep default methods short. • Use private methods to extract shared core of default methods. • Don’t use default methods to extend existing interfaces unless necessary. • Use default methods for providing standard implementations for new interface code. • More info: JEP 213: Milling Project Coin. Lesson 4: Private methods in interfaces
  34. 34. @mirocupak !34 Stream API enhancements Lesson 5
  35. 35. @mirocupak Lesson 5: Stream API enhancements !35 Task 5.1 Modify the stream below to only print the numbers <5 (>5). IntStream.range(0,10).forEach(System.out::println)
  36. 36. @mirocupak Lesson 5: Stream API enhancements !36 Task 5.2 Demonstrate a difference between filter and takeWhile (dropWhile). Hint: Print even numbers <100.
  37. 37. @mirocupak Lesson 5: Stream API enhancements !37 Task 5.3 Improve the code from the previous task.
  38. 38. @mirocupak Lesson 5: Stream API enhancements !38 Task 5.4 Come up with a scenario where ofNullable helps.
  39. 39. @mirocupak Lesson 5: Stream API enhancements !39 Task 5.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.
  40. 40. @mirocupak Lesson 5: Stream API enhancements !40 Task 5.6 Suppose we have the following stream of mappings of integers to sets of strings (for simplicity represented as Map entries): Stream.of(entry(1, Set.of("a", "b")), entry(1, Set.of("a", "c")), entry(2, Set.of("d"))) Aggregate this data - group the strings by the integers they’re associated with. Hint: flatMapping.
  41. 41. @mirocupak Lesson 5: Stream API enhancements !41 Task 5.7 Show that the new immutable collectors generate immutable collections.
  42. 42. @mirocupak Lesson 5: Stream API enhancements !42 Task 5.8 Explore how the pattern matching API plays nicely with streams. Hint: Use Matcher to obtain all results of a match.
  43. 43. @mirocupak Lesson 5: Stream API enhancements !43 Task 5.9 Explore how the date-time API plays nicely with streams. Hint: Use LocalDate to obtain list of dates between now and Christmas.
  44. 44. @mirocupak !44 • 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. Lesson 5: Stream API enhancements
  45. 45. @mirocupak !45 Extensions to Optional Lesson 6
  46. 46. @mirocupak Lesson 6: Extensions to Optional !46 Task 6.1 Given an Optional, print its value if the value is present, otherwise print “empty”.
  47. 47. @mirocupak Lesson 6: Extensions to Optional !47 Task 6.2 What other methods in the Optional API are similar to or?
  48. 48. @mirocupak Lesson 6: Extensions to Optional !48 Task 6.3 Another 2 methods in the same family were added in Java 10. Can you find them?
  49. 49. @mirocupak Lesson 6: Extensions to Optional !49 Task 6.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.
  50. 50. @mirocupak !50 • 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. Lesson 6: Extensions to Optional
  51. 51. @mirocupak !51 CompletableFuture updates Lesson 7
  52. 52. @mirocupak Lesson 7: CompletableFuture updates !52 Task 7.1 completeOnTimeout is great for completing a future normally based on a timeout. How do I complete a future exceptionally based on a timeout?
  53. 53. @mirocupak Lesson 7: CompletableFuture updates !53 Task 7.2 Inspect the contract of the copy method. Demonstrate the one-way synchronization it provides.
  54. 54. @mirocupak Lesson 7: CompletableFuture updates !54 Task 7.3 Take some time to explore other new additions to the CompletableFuture API we haven’t talked about.
  55. 55. @mirocupak !55 • 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. Lesson 7: CompletableFuture updates
  56. 56. @mirocupak !56 StackWalker Lesson 8
  57. 57. @mirocupak Lesson 8: StackWalker !57 Task 8.1 How did we access stack traces prior to Java 9? What are the problems with this approach?
  58. 58. @mirocupak Lesson 8: StackWalker !58 Task 8.2 Obtain top 3 elements of your current stack lazily. Hint: streams.
  59. 59. @mirocupak Lesson 8: StackWalker !59 Task 8.3 Obtain only elements in the stack related to jdk.jshell.execution.Util class.
  60. 60. @mirocupak !60 • Prefer collections and streams to arrays. • Access stack traces lazily via walk. • Take advantage of the Stream API to access only certain elements. • Be aware of StackWalker.Option. • Don’t resolve classes manually. • Use to show hidden and reflection frames. • More info: JEP 259: Stack-Walking API. Lesson 8: StackWalker
  61. 61. @mirocupak !61 Process API Lesson 9
  62. 62. @mirocupak Lesson 9: Process API !62 Task 9.1 Launch an external process from Java. What are the problems with this API?
  63. 63. @mirocupak Lesson 9: Process API !63 Task 9.2 List all the commands running in your OS visible to you. Hint: allProcesses.
  64. 64. @mirocupak Lesson 9: Process API !64 Task 9.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.
  65. 65. @mirocupak Lesson 9: Process API !65 Task 9.4 List your currently running Java processes with jps. Use grep to find JShell in the list. Hint: startPipeline.
  66. 66. @mirocupak !66 • 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. Lesson 9: Process API
  67. 67. @mirocupak !67 HTTP/2 client Lesson 10
  68. 68. @mirocupak !68 Task 10.1 Load the HTTP/2 client module (jdk.incubator.httpclient) and import the necessary classes (jdk.incubator.http.*). Lesson 10: HTTP/2 client
  69. 69. @mirocupak !69 Task 10.2 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. Lesson 10: HTTP/2 client
  70. 70. @mirocupak !70 Task 10.3 Use the new HTTP/2 client API to execute a request against a server asynchronously. Read the response. Lesson 10: HTTP/2 client
  71. 71. @mirocupak !71 Task 10.4 Explore the rest of the HTTP/2 client API. Lesson 10: HTTP/2 client
  72. 72. @mirocupak Lesson 10: HTTP/2 client !72 • 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. • But aware it’s an incubator module. • More info: JEP 110: HTTP 2 Client.
  73. 73. @mirocupak !73 Type inference Lesson 11
  74. 74. @mirocupak !74 Task 11.1 Create an anonymous class with the <> operator. Hint: Functional interfaces are simple. Lesson 11: Type inference
  75. 75. @mirocupak !75 Task 11.2 Which of the following snippets work? Hint: All of them would work with explicit types. Lesson 11: Type inference (1) var x=0,y=0 (2) int inc(var x) { return x+1; } (3) var inc(int x) { return x+1; } (4) var x (5) var x = null (6) var x = (Integer) null (7) var[] x = {1,2} (1) var x = {1,2} (2) var x = new int[] {1,2} (3) try {} catch (var ex) {} (4) var s = () -> “" (5) var c = System.out::println (6) var list = new ArrayList<>() (8) var list = new ArrayList<>(Set.of(1))
  76. 76. @mirocupak !76 Task 11.3 What happens in the following example? What if we declare intPair with var? Object intPair = new Object() { int left = 1; int right = 2; } intPair.left Lesson 11: Type inference
  77. 77. @mirocupak Lesson 11: Diamond operator with anonymous classes !77 • Use <> for anonymous classes, like everywhere else. • <> improves readability and consistency. • Use anonymous classes only when needed (e.g. abstract classes, interfaces with multiple abstract methods…), otherwise replace with lambdas. • More info: JEP 213: Milling Project Coin.
  78. 78. @mirocupak Lesson 11: Local variable type inference !78 • Does not replace static typing. • Generally good. • Reduces boilerplate and improves readability. • Helps with maintenance and refactoring. • Use for local variables with initializers (especially constructors) and for loops. • Can’t use for method formals, constructor formals, method return types, fields, catch formals, null or array initializers, lambdas, method references, or any other kind of variable declaration. • Consider whether to use when the generated type is not obvious. • But use for complex types when breaking chained or nested expressions with local variables. • Primitive types might surprise you, be careful (e.g. byte, short, long all inferred as int).
  79. 79. @mirocupak !79 • Be very careful about combining with <> and generic methods (e.g. var list = new ArrayList<>()). • Probably not the best idea to use with anonymous classes. • Use carefully chosen and expressive variable names. • 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. • Code to the interface pattern does not work, but that’s kind of OK. • More info: JEP 286: Local-Variable Type Inference. Lesson 11: Local variable type inference
  80. 80. @mirocupak !80 Modularity Lesson 12
  81. 81. @mirocupak !81 Task 11.1 Use the java command to find dependencies of the java.sql module. Lesson 12: Modularity
  82. 82. @mirocupak !82 Task 11.2 Create your own module. Try other directives to learn more about modules and how they work. Lesson 12: Modularity
  83. 83. @mirocupak !83 • More info: • JEP 200: The Modular JDK • JEP 201: Modular Source Code • JEP 220: Modular Run-Time Images • JEP 260: Encapsulate Most Internal APIs • JEP 261: Module System • JEP 275: Modular Java Application Packaging • JEP 282: jlink: The Java Linker Lesson 12: Modularity
  84. 84. @mirocupak Questions? !84 https://mirocupak.com/

×