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

What's new on JDK 10 & 11

What's new on JDK 10 & 11

This presentation talks about the new features on JDK 10 and 11 that are useful for developers. It is focused on features that affect how you code, new APIs and some interesting points.

This was presented as a lightning talk during the PegaSys offsite 2018.

Lucas Saldanha

November 05, 2018
Tweet

More Decks by Lucas Saldanha

Other Decks in Programming

Transcript

  1. Features Overview JDK 10 Development • Local-Variable Type Inference (JEP

    286) Others • Garbage collector interface (JEP 304) • Improvements on running Java applications on Docker containers JDK 11 Development • Local-Variable Type Inference for Lambda Parameters (JEP 323) • Single-file Programs (JEP 330) • HTTP Client (JEP 321) • New String and Files methods • More API changes worth mentioning Others • Epsilon GC (JEP 318) • ZGC (JEP 333)
  2. Local-Variable Type Inference
 (JEP 286) • Use of var for

    local variables • Compiler infers variable type checking the RHS of the expression • No dynamic typing • Better development experience • Good usages: ◦ Simple local variables ◦ Loops ◦ Try-with-resources blocks var year = 2018;
 var names = new ArrayList<String>();
 
 for (var i = 0; i < names.size(); i++) {
 var name = names.get(i);
 // do something
 }
 
 var file = new File("/tmp/foo.txt");
 try (var fis = new FileInputStream(file)) {
 // read file
 } catch (IOException e) {
 e.printStackTrace();
 }
  3. Local-Variable Type Inference
 (JEP 286) • Can’t be used: ◦

    Without initialiser ◦ Initialised as null ◦ Multiple variable definition ◦ Array initialiser (brackets) ◦ Lambda expressions ◦ Method references • Can’t be used with parameters of lambda expressions (JDK 10) • Be careful with <> operator var age;
 
 var name = null;
 
 var x = 10, y = 9;
 
 var numbers = {1, 2 ,3};
 
 var maxFunction = (a, b) -> a > b ? a : b;
 
 var minFunction = Math::min;
  4. Local-Variable Type Inference
 (JEP 286) • Can’t be used: ◦

    Without initialiser ◦ Initialised as null ◦ Multiple variable definition ◦ Array initialiser (brackets) ◦ Lambda expressions ◦ Method references • Can’t be used with parameters of lambda expressions (JDK 10) • Be careful with <> operator var names = new ArrayList<String>(); List<String> names = new ArrayList<>(); var names = new ArrayList<>();
  5. Local-Variable Type Inference for Lambda Parameters
 (JEP 323) • Brings

    var syntax to the parameter of lambda expressions • Not that useful for most lambdas • Specially useful for using annotations with parameters in lambda expressions var names = Arrays.asList("Lucas", "Rob", "Brett");
 
 names.stream()
 .filter((@NotNull var n) -> n.startsWith("L"))
 .forEach(System.out::println);
  6. Local-Variable Type Inference for Lambda Parameters
 (JEP 323) • Brings

    var syntax to the parameter of lambda expressions • Not that useful for most lambdas • Specially useful for using annotations with parameters in lambda expressions var names = Arrays.asList("Lucas", "Rob", "Brett");
 
 names.stream()
 .filter((@NotNull var n) -> n.startsWith("L"))
 .forEach(System.out::println); names.stream()
 .filter(n -> n.startsWith("L"))
 .forEach(System.out::println);
  7. Launch Single-file Source-code Programs
 (JEP 330) • The “ceremony” to

    run a Java application is not trivial • Compile and run Java program with one command • Supports “shebang” operator • Good for people learning Java • Really useful for simple scripts (automation) //HelloWorld.java public class HelloWorld {
 public static void main(String[] args) {
 System.out.println("Hello, World!");
 }
 } $ java HelloWorld.java > Hello, World!
  8. Launch Single-file Source-code Programs
 (JEP 330) • The “ceremony” to

    run a Java application is not trivial • Compile and run Java program with one command • Supports “shebang” operator • Good for people learning Java • Really useful for simple scripts (automation) #!/usr/bin/java --source 11 public class Shebang { public static void main(String[] args) { System.out.println(“Hello, Wolrd!"); } } $ ./shebang > Hello, World!
  9. HTTP Client (Standard)
 (JEP 321) • Started on JDK 9

    as an incubated feature (JEP 110) • Bye bye HttpUrlConnection API • Main types ◦ HttpClient ◦ HttpRequest ◦ HttpResponse ◦ WebSocket • Support synchronous and asynchronous requests @Test
 public void getPeerNumber_oldWay() throws Exception {
 String requestBody = "{ \"method\": \"net_peerCount\", \"id\": 1 }";
 
 URL url = new URL("http://127.0.0.1:8545");
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 conn.setRequestMethod("POST");
 conn.setRequestProperty("Content-Type", "application/json");
 conn.setDoOutput(true);
 
 try (OutputStreamWriter writer =
 new OutputStreamWriter(conn.getOutputStream())) {
 writer.write(requestBody);
 writer.flush();
 String line;
 BufferedReader reader = new BufferedReader(
 new InputStreamReader(conn.getInputStream()));
 while ((line = reader.readLine()) != null) {
 System.out.println(line);
 }
 reader.close();
 }
 assertThat(conn.getResponseCode()).isEqualTo(200);
 }
  10. HTTP Client (Standard)
 (JEP 321) • Started on JDK 9

    as an incubated feature (JEP 110) • Bye bye HttpUrlConnection API • Main types ◦ HttpClient ◦ HttpRequest ◦ HttpResponse ◦ WebSocket • Support synchronous and asynchronous requests @Test
 public void getPeerNumber_newWay() throws Exception {
 String requestBody = "{ \"method\": \"net_peerCount\", \"id\": 1 }";
 
 HttpRequest request = HttpRequest.newBuilder()
 .uri(URI.create("http://127.0.0.1:8545"))
 .POST(HttpRequest.BodyPublishers.ofString(requestBody))
 .header("Content-Type", "application/json")
 .build();
 
 HttpResponse<String> response = HttpClient.newHttpClient()
 .send(request, HttpResponse.BodyHandlers.ofString());
 
 System.out.println(response.body());
 
 assertThat(response.statusCode()).isEqualTo(200);
 }
  11. HTTP Client (Standard)
 (JEP 321) • Started on JDK 9

    as an incubated feature (JEP 110) • Bye bye HttpUrlConnection API • Main types ◦ HttpClient ◦ HttpRequest ◦ HttpResponse ◦ WebSocket • Support synchronous and asynchronous requests @Test
 public void getPeerNumber_newWay_Async() {
 String requestBody = "{ \"method\": \"net_peerCount\", \"id\": 1 }";
 
 HttpRequest request = HttpRequest.newBuilder()
 .uri(URI.create("http://127.0.0.1:8545"))
 .POST(HttpRequest.BodyPublishers.ofString(requestBody))
 .header("Content-Type", "application/json")
 .build();
 
 HttpClient.newHttpClient()
 .sendAsync(request, BodyHandlers.ofString())
 .thenAccept(response -> {
 System.out.println(response.body());
 assertThat(response.statusCode()).isEqualTo(200);
 });
 }
  12. New String and Files methods String • strip() / stripLeading()

    / stripTrailing() ◦ Removes spaces (Unicode aware) • isBlank() ◦ Test if the string is empty or contains only whitespaces • lines() ◦ Return a Stream of lines extracted from the string • repeat(int) ◦ Returns a new string whose value is the string concatenated n times Files • readString(Path) ◦ Reads a file into a string (UTF-8 decoding) ◦ Overloaded options for decoding with other Charset • writeString(Path, ...) ◦ Write a CharSequence to a file (UTF-8 encoding) ◦ Overloaded option for encoding with other Charset • isSameFile(Path, Path) ◦ Tests if two paths locate the same file ◦ Doesn’t test file content (!)
  13. Interesting API Changes • Thread ◦ Methods destroy() and stop(Throwable)

    have been removed ◦ Spoiler alert: they haven’t done anything useful since JDK 8
 • Optional.isEmpty() ◦ Tests if a value is NOT present ◦ Good for readability
 • TimeUnit.convert(Duration) ◦ Converts a duration to this time unit
 • Predicate.not(Predicate) ◦ Creates a predicate that is the negative of the predicate parameter
  14. “Non-development” Changes • GarbageCollector interface (JEP 304) ◦ Improves source

    code isolation for different GC implementations
 • Improvements for running Java application on Docker ◦ Java will respect the limits set by the container
 • Epsilon GC (JEP 318) ◦ A garbage collector that “does nothing”
 • ZGC (JEP 333) ◦ A scalable low-latency garbage collector
  15. References • JDK 10 Release Notes • JDK 11 Release

    Notes • Java 10: New Features and Enhancements • Java 10: Local-Variable Type Inference • Docker and Java 10 • Java 10 changes to CG explained in 5 minutes • New Features and APIs in Java 11 (Part 1) • New Features and APIs in Java 11 (Part 2) • Java 11 Standardized Http Client API • Java 11 String Changes • Java JEP Index (contains links to all JEP’s)