Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Preparing for the Java 21 Certification and Learning New Features

Preparing for the Java 21 Certification and Learning New Features

Learning about virtual threads, pattern matching for switch, record patterns and sequenced collections

Jeanne Boyarsky

April 11, 2024
Tweet

More Decks by Jeanne Boyarsky

Other Decks in Technology

Transcript

  1. https://linktr.ee/jeanneboyarsky 1 Preparing for the Java 21 cert + Learning

    New Features Jeanne Boyarsky 4/11/24 DevNexus speakerdeck.com/boyarsky
  2. https://linktr.ee/jeanneboyarsky Disclaimer 3 I do not work for Oracle so

    no safe harbor statement. However, I am not authorized to tell you any non public information or if I know any :) Some of the material in this presentation may appear in our upcoming certification books.
  3. https://linktr.ee/jeanneboyarsky Strategy 4 Option 1 - wait for Java 21

    study materials Option 2: 1. Study from a Java 17 study guide 2. Read about Java 18-21 features 3. Focus on edge cases 4. Do any practice questions you can find This talk helps with option 2. Or if you just want to learn
  4. https://linktr.ee/jeanneboyarsky Agenda 5 Topics Chances of being in objectives Virtual

    threads 95% or higher Pattern matching for switch 95% or higher Record patterns 95% or higher Sequenced Collections 10-30% Other topics + open Q&A less than 5%
  5. https://linktr.ee/jeanneboyarsky Why we need threads 8 Program Do calculation and

    call REST API Do calculation and call REST API CPU Network I’m bored… I’m waiting for a reply
  6. https://linktr.ee/jeanneboyarsky Why we need virtual threads 9 Program Do calculation

    and call REST API Proceed CPU Network Still bored… Still waiting for a reply Platform Thread 1 Platform Thread n Do calculation and call REST API Send to threads
  7. https://linktr.ee/jeanneboyarsky Virtual Thread 1 With virtual threads 10 Program Do

    calculation and call REST API Proceed CPU Network Thanks for the work! Me too! Platform Thread 1 Platform Thread n Send to threads Virtual Thread t Do calculation and call REST API Virtual Thread t+1 Do calculation and call REST API Virtual Thread x Do calculation and call REST API
  8. https://linktr.ee/jeanneboyarsky Comparing 12 Platform (Traditional) Thread Virtual Thread Heavyweight Lightweight

    Tied to OS threads Runs on OS thread but doesn’t monopolize Often pooled Often shortlived Instance of java.lang.Thread Instance of java.lang.Thread 21
  9. https://linktr.ee/jeanneboyarsky Fill in the blank 13 try (ExecutorService service =

    Executors._________) { service.submit(() -> doStuff()); } Examples: • newSingleThreadExecutor() • newFixedThreadPool(5) • newCachedThreadPool() • newVirtualThreadPerTaskExecutor() 21
  10. https://linktr.ee/jeanneboyarsky Autocloseable 14 Method Java 21 shutdown() No more tasks,

    but finish ones have shutdownNow() Stop tasks in progress close() Calls shutdown by default 19
  11. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #1 17 Which is used to

    create/with a virtual thread? (more than 1 is correct) A. Executors.newVirtualThread() B. Executors.newVirtualThreadExecutor() C. Executors.newVirtualThreadPerTaskExecutor() D. new VirtualThread() E. Thread.ofVirtual() F. Thread.ofVirtualThread() 21
  12. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #1 18 Which is used to

    create/with a virtual thread? (more than 1 is correct) A. Executors.newVirtualThread() B. Executors.newVirtualThreadExecutor() C. Executors.newVirtualThreadPerTaskExecutor() D. new VirtualThread() E. Thread.ofVirtual() F. Thread.ofVirtualThread() 21 C, E
  13. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #2 19 Which is used to

    create/with a platform thread? (more than 1 is correct) A. Executors.newCachedThreadPool() B. Executors.newPlatformThreadPool() C. Executors.newPlatformThreadPerTaskExecutor() D. new Thread() E. new PlatformThread() F. Thread.ofPlatform() 21
  14. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #2 20 Which is used to

    create/with a virtual thread? (more than 1 is correct) A. Executors.newCachedThreadPool() B. Executors.newPlatformThreadPool() C. Executors.newPlatformThreadPerTaskExecutor() D. new Thread() E. new PlatformThread() F. Thread.ofPlatform() 21 A, D, F
  15. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #3 21 What is true doStuff()

    at line v1? try (var service = Executors.newVirtualThreadPerTaskExecutor()) { service.submit(() -> doStuff()); } // line v1 A. doStuff() may be running B. doStuff() was killed C. doStuff() completed D. None of the above 21
  16. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #3 22 What is true doStuff()

    at line v1? try (var service = Executors.newVirtualThreadPerTaskExecutor()) { service.submit(() -> doStuff()); } // line v1 A. doStuff() may be running B. doStuff() was killed C. doStuff() completed D. None of the above 21 C
  17. https://linktr.ee/jeanneboyarsky Evolution 24 Feature Preview Final Switch Expressions 12, 13

    14 Pattern Matching for instanceof 14, 15 16 Pattern Matching for switch 17, 18, 19, 20 21 Record Patterns 19, 20 21 Unnamed variables and patterns 21 22
  18. @jeanneboyarsky What does this print? 14 String place = "Vegas";

    switch(place) { case "Vegas" : System.out.println("Table games!"); case "Supermarket" : System.out.println("Lotto!"); default: System.out.println("Maybe?"); } Three lines (missing break) 25
  19. @jeanneboyarsky Switch Expressions String place = "Vegas"; switch(place) { case

    "Vegas" -> System.out.println("Table Games!"); case "Supermarket", "Newsstand" -> System.out.println("Lotto!"); default -> System.out.println("anywhere"); } 26 14 Arrow labels No break keyword Multiple values
  20. @jeanneboyarsky Switch Expressions String place = "Vegas"; var output =

    switch(place) { case "Vegas" -> "Table Games!"; case "Supermarket", "Newsstand" -> "Lotto!"; default -> "anywhere"; }; System.out.println(output); Switch returns values 27 14 Semicolon
  21. @jeanneboyarsky Adding Pattern Matching 28 21 return switch (obj) {

    case null -> ""; case Integer i when i >= 21 -> "can gamble"; case Integer i -> "too young to gamble"; case String s when "poker".equals(s) -> "table game"; case String s when "craps".equals(s) -> "table game"; case String s -> "other game"; default -> throw new IllegalArgumentException("unexpected type"); }; guard clause pattern variable null allowed Still Null Pointer if don’t specify case null
  22. @jeanneboyarsky Order matters 29 21 return switch (obj) { case

    null -> ""; case Integer i -> "too young to gamble"; case Integer i when i >= 21 -> "can gamble”; // DOES NOT COMPILE case String s -> "other game"; default -> throw new IllegalArgumentException("unexpected type"); }; Order like catching exceptions!
  23. @jeanneboyarsky Enums 30 21 enum Suit { HEART, DIAMOND, CLUB,

    SPADE; } String symbol(Suit suit) { return switch (suit) { case HEART -> "♥"; case Suit.DIAMOND -> "♦"; case CLUB -> "♣"; case Suit.SPADE -> "♠"; }; } Fails compilation if miss one since no default
  24. @jeanneboyarsky Switch statements 31 21 boolean idCheck(Integer age) { boolean

    check ; switch (age) { case Integer i when i <= 40 : check = true; break; default : check = false; break; } return check; } Yes, classic switch
  25. @jeanneboyarsky Pattern variable scope 32 21 boolean idCheck(Integer age) {

    boolean check ; switch (age) { case Integer i when i <= 21 : check = true; // DOES NOT COMPILE case Integer i when i <= 40 : check = true; default : check = false; } return check; } Can’t use pattern variable if fall thru
  26. https://linktr.ee/jeanneboyarsky What can’t you do? 33 • In switch(x), x

    still can’t be • boolean • float • double • long • _ as pattern (coming in Java 22) 21
  27. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #1 34 What is minimum

    # lines do you need to remove to make this code compile? double odds(Object obj) { return switch (obj) { case String s -> throw new IllegalArgumentException("unknown game"); case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case Object o -> throw new IllegalArgumentException("unknown game"); default -> throw new IllegalArgumentException("known game"); }; } A. 0 B. 1 21 C. 2 D. 3
  28. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #1 35 How many lines

    do you need to remove to make this code compile? double odds(Object obj) { return switch (obj) { case String s -> throw new IllegalArgumentException("unknown game"); case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case Object o -> throw new IllegalArgumentException("unknown game"); default -> throw new IllegalArgumentException("known game"); }; } A. 0 B. 1 21 C. 2 D. 3 C String s & Object o or default
  29. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #2 36 What are the

    results of odds(“slots”) and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game"); }; } A. IllegalArgumentException B. NullPointerException 21 C. .05 D. Does not compile
  30. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #2 37 What are the

    results of odds(“slots”) and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game"); }; } A. IllegalArgumentException B. NullPointerException 21 C. .05 D. Does not compile A, B
  31. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #3 38 What are the

    results of odds("slots") and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game”); case null -> 0.0; }; } A. IllegalArgumentException B. NullPointerException 21 C. 0.0 D. Does not compile
  32. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #3 39 What are the

    results of odds("slots") and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game”); case null -> 0.0; }; } A. IllegalArgumentException B. NullPointerException 21 C. 0.0 D. Does not compile A, C
  33. https://linktr.ee/jeanneboyarsky Record Patterns 41 enum Suit { HEART, DIAMOND, CLUB,

    SPADE; } enum Rank { NUM_2, NUM_3, NUM_4, NUM_5, NUM_6, NUM_7 NUM_8, NUM_9, NUM_10, JACK, QUEEN, KING, ACE; } record Card(Suit suit, Rank rank) { } if (card instanceof Card c) { System.out.println(c.suit()); System.out.println(c.rank()); } if (card instanceof Card(Suit suit, Rank rank)) { System.out.println(suit); System.out.println(rank); } 21 Deconstructed
  34. https://linktr.ee/jeanneboyarsky Nested Record Patterns 42 record MultiDeck(int deckNum, Card card)

    { } if (multi instanceof MultiDeck(int deckNum, Card(Suit suit, Rank rank))) { System.out.println(deckNum); System.out.println(suit); System.out.println(rank); } 21
  35. https://linktr.ee/jeanneboyarsky Switch pattern matching 43 switch(card) { case Card(Suit suit,

    Rank rank) when suit == Suit.HEART -> System.out.println("Heart"); case Card c -> System.out.println("other"); } 21
  36. https://linktr.ee/jeanneboyarsky Switch pattern matching 44 String str = ""; switch

    (str) { case "heart" -> System.out.println("heart"); } Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(Suit suit, Rank rank) when suit == Suit.HEART -> System.out.println("Heart"); case Card c -> System.out.println("other"); } 21 Must be exhaustive if using “when”
  37. https://linktr.ee/jeanneboyarsky Record Patterns Mock #1 46 Which of these compile?

    (more than one) A. if (card instanceof Card (Suit suit, Rank rank)) { } B. if (card instanceof Card (var suit, var rank)) { } C. if (card instanceof Card c) { } D. if (card instanceof Card c.suit, c.rank) { } 21
  38. https://linktr.ee/jeanneboyarsky Record Patterns Mock #1 47 Which of these compile?

    (more than one) A. if (card instanceof Card (Suit suit, Rank rank)) { } B. if (card instanceof Card (var suit, var rank)) { } C. if (card instanceof Card c) { } D. if (card instanceof Card c.suit, c.rank) { } 21 A, B, C
  39. https://linktr.ee/jeanneboyarsky Record Patterns Mock #2 48 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); } A. Ace of Hearts B. Hearts 21 C. Null Pointer D. Does not compile
  40. https://linktr.ee/jeanneboyarsky Record Patterns Mock #2 49 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); } A. Ace of Hearts B. Hearts 21 C. Null Pointer D. Does not compile D (no case Card)
  41. https://linktr.ee/jeanneboyarsky Record Patterns Mock #3 50 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); case Card c -> System.out.println("other"); } 21 A. Ace of Hearts B. Hearts C. Null Pointer D. Does not compile
  42. https://linktr.ee/jeanneboyarsky Record Patterns Mock #3 51 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); case Card c -> System.out.println("other"); } 21 A. Ace of Hearts B. Hearts C. Null Pointer D. Does not compile B
  43. https://linktr.ee/jeanneboyarsky Record Patterns Mock #4 52 Given record Card (Suit

    suit, Rank rank), how many of these compile? case Card(var rank, var suit) when suit == Suit.HEART case Card(Rank rank, Suit suit) when suit == Suit.HEART case Card(Rank rank, var suit) when suit == Suit.HEART case Card(var suit, var rank) when suit == Suit.HEART case Card(Suit suit, Rank rank) when suit == Suit.HEART case Card(var suit, Rank rank) when suit == Suit.HEART A. 0 B. 1 C. 2 21 D. 3 E. 4 F. 5
  44. https://linktr.ee/jeanneboyarsky Record Patterns Mock #4 53 Given record Card (Suit

    suit, Rank rank), how many of these compile? case Card(var rank, var suit) when suit == Suit.HEART case Card(Rank rank, Suit suit) when suit == Suit.HEART case Card(Rank rank, var suit) when suit == Suit.HEART case Card(var suit, var rank) when suit == Suit.HEART case Card(Suit suit, Rank rank) when suit == Suit.HEART case Card(var suit, Rank rank) when suit == Suit.HEART A. 0 B. 1 21 C. 2 D. 3 D (last three)
  45. https://linktr.ee/jeanneboyarsky What does this output? 55 HashSet<String> set = new

    HashSet<>(); set.add("Donald"); set.add("Mickey"); set.add("Minnie"); System.out.println(set.iterator().next()); Encounter order undefined(but Mickey on my machine) 21
  46. https://linktr.ee/jeanneboyarsky New APIs 58 SequencedCollection SequencedCollection <E> reversed(); void addFirst(E);

    void addLast(E); E getFirst(); E getLast(); E removeFirst(); E removeLast(); SequencedSet SequencedSet<E> reversed(); SequencedMap SequencedMap<K,V> reversed(); SequencedSet<K> sequencedKeySet(); SequencedCollection<V> sequencedValues(); SequencedSet<Entry<K,V>> sequencedEntrySet(); V putFirst(K, V); V putLast(K, V); Entry<K, V> fi rstEntry(); Entry<K, V> lastEntry(); Entry<K, V> pollFirstEntry(); Entry<K, V> pollLastEntry(); 21
  47. https://linktr.ee/jeanneboyarsky Now defined! 59 SequencedSet<String> set = new LinkedHashSet<>(); set.add("Donald");

    set.add("Mickey"); set.add("Minnie"); System.out.println(set.getFirst()); Donald Note: LInkedHashSet not new 21
  48. https://linktr.ee/jeanneboyarsky Sequenced Collection Mock 60 How many of these lines

    compile? SequencedCollection<Integer> seq1 = new HashSet<>(); SequencedSet<Integer> seq2 = new HashSet<>(); SequencedMap<Integer> seq3 = new HashSet<>(); SequencedCollection<Integer> seq4 = new TreeSet<>(); SequencedSet<Integer> seq5 = new TreeSet<>(); SequencedMap<Integer> seq6 = new TreeSet<>(); A. One B. Two C. Three D. Four 21
  49. https://linktr.ee/jeanneboyarsky Sequenced Collection Mock 61 How many of these lines

    compile? SequencedCollection<Integer> seq1 = new HashSet<>(); SequencedSet<Integer> seq2 = new HashSet<>(); SequencedMap<Integer> seq3 = new HashSet<>(); SequencedCollection<Integer> seq4 = new TreeSet<>(); SequencedSet<Integer> seq5 = new TreeSet<>(); SequencedMap<Integer> seq6 = new TreeSet<>(); A. One B. Two C. Three D. Four B (seq4 and seq 5) 21
  50. https://linktr.ee/jeanneboyarsky Good to know, but not likely on exam 62

    • UTF-8 is the default character set when reading a file • StringBuilder/StringBuffer have a repeat method • String.indexOf(charOrStr, beginIndex, endIndex) • String.splitWithDelimitters(regex, limit) • Finalization deprecated for removal
  51. https://linktr.ee/jeanneboyarsky Good to know, but not likely on exam 63

    Code Snippets in JavaDoc Inline * {@snippet : * if (v.isPresent()) { * System.out.println("v: " + v.get()); * } * } External {@snippet fi le="ShowOptional.java" region=“example"} Example transformation System.out.println("Hello World!"); // @highlight substring="println"