class: center, middle, inverse background-image: url(bekklogo-white.png) background-position: center 20px background-repeat: no-repeat background-size: 250px # Java 9 - what else is new? ## Jan Fredrik Wedén ??? Hei, jeg heter Jan Fredrik, jobber i BEKK og skal snakke litt om Java 9. Si noe om at Jigsaw har de fleste hørt om. Nå skal vi se på noen av de andre tingene som er nye. --- class: center, middle # Java Shell (`jshell`)! ??? Vi har endelig fått en REPL for Java! --- # jshell - some features - Trying out snippets of code - Tab completion for snippets and commands - Changing definitions - Forward references - Editing and searching in shell, like you expect - External editor with **`/edit`** - Loading external code through classpath or module path - Saving and loading external scripts ??? Verdt å nevne at shell editing fungerer alla BSD editline/GNU readline med navigering i history etc (Ctr-arrow for navigering pr snippet og ikke pr linje) --- # Some jshell commands - **`/exit`** - first thing to know is how to get out (`^D` also works) - **`/help`** - list of available commands - **`/list`** - lists all snippets - **`/save /open`** - save and open snippets to and from disk - **`/vars /types /methods`** - list current vars etc --- class: center, middle # Immutable collections --- # Collections (old school) ``` Set
set = new HashSet<>(); set.add("Java"); set.add("eight"); set.add("collections"); set = Collections.unmodifiableSet(set); ``` -- ``` Set
set = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("Java", "eight", "collections"))); ``` -- ``` Set
set = Collections.unmodifiableSet(new HashSet
() {{ add("Java"); add("eight"); add("collections"); }}); ``` -- ``` Set
set = Collections.unmodifiableSet(Stream.of("Java", "eight", "collections").collect(toSet())); ``` -- ## Guava anyone?? --- # New collection factory methods ``` Set
mySet = Set.of("Java", "nine", "collections"); ``` -- ``` List
myList = List.of("Java", "nine", "collections"); ``` -- ``` Map
myMap = Map.of("Duke", "Java", "coolest", "nine", "better", "collections"); ``` -- ``` Map
myEntryMap = Map.ofEntries( Map.entry("Duke", "Java"), Map.entry("coolest", "nine"), Map.entry("better", "collections") ); ``` ??? Det Java nå har fått ligner jo mistenkelig på Guava, men vi har altså fått det natively i JDK-en og slipper å importere noe som helst. Men ikke like kraftig som Guava's Builder-classes. --- # Such collections - Are structurally immutable (mutators throw `UnsupportedOperationException`) - Disallow `null` elements (and keys) - Are serializable if all elements (and keys) are - Sets and Maps throw `IllegalArgumentException` for duplicate elements/keys at creation time - Iteration order of Lists behave as expected and is undefined for Sets and Maps - Are value based (you should not rely on `==`) --- class: center, middle # `Optional` stuff --- # New methods on `Optional` ``` public void ifPresentOrElse(Consumer super T> action, Runnable emptyAction) ``` ??? If a value is present, performs the given action with the value, otherwise performs the given empty-based action. -- ``` public Optional
or(Supplier extends Optional extends T>> supplier) ``` ??? If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function. -- ``` public Stream
stream() ``` ??? If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream. This method can be used to transform a Stream of optional elements to a Stream of present value elements: -- ``` List
> optionals = List.of( Optional.of("Java"), Optional.of("nine"), Optional.empty(), Optional.of("Optional") ); System.out.println("Optionals in list:") optionals.stream().forEach(System.out::println) System.out.println("All Optional values (or null):") optionals.stream().map(o -> o.orElse(null)).forEach(System.out::println) System.out.println("Only present Optional values:") *optionals.stream().flatMap(Optional::stream).forEach(System.out::println) ``` --- class: center, middle # I/O and resources --- # I/O and resources - "Effectively final" variables allowed in try-with-resources ``` void copyFile(InputStream in, OutputStream out) throws IOException { * try (in; out) { in.transferTo(out); } } InputStream inFile = Files.newInputStream(Paths.get("in.txt")); OutputStream outFile = Files.newOutputStream(Paths.get("out.txt")); copyFile(inFile, outFile); try (InputStream inFileAgain = Files.newInputStream(Paths.get("in.txt"));) { byte[] allBytes = inFileAgain.readAllBytes(); } ``` --- # I/O and resources - New methods on `InputStream` ``` void copyFile(InputStream in, OutputStream out) throws IOException { try (in; out) { * in.transferTo(out); } } InputStream inFile = Files.newInputStream(Paths.get("in.txt")); OutputStream outFile = Files.newOutputStream(Paths.get("out.txt")); copyFile(inFile, outFile); try (InputStream inFileAgain = Files.newInputStream(Paths.get("in.txt"));) { * byte[] allBytes = inFileAgain.readAllBytes(); } ``` --- class: center, middle # HTTP/2 --- # New HTTP client in Java! - Supports HTTP/2 and WebSockets - Supports sync and async request modes - Supports multiple HTTP/2 push responses - Replaces the legacy `HttpURLConnection` --- # Caveats - Incubator module - Not all (expected) features currently available - Apparently vulnerable to attacks (BREACH and CRIME) - Apparently sloppy about cookie security - HTTP/1.1 encryption --- # `HttpClient` Example ``` import jdk.incubator.http.*; HttpClient.newHttpClient() .sendAsync( HttpRequest.newBuilder(URI.create("https://www.google.no")) .GET() .build(), HttpResponse.BodyHandler.asString()) .thenAccept(response -> System.out.println(response.statusCode())); ``` -- ### Must add incubator module to `jshell` When starting: ```bash $ jshell --add-modules jdk.incubator.httpclient ``` Or inside `jshell` ``` jshell> /env -add-modules jdk.incubator.httpclient ``` --- class: center, middle # Deprecation ## Stuff is actually going to be removed from Java! --- # Enhanced `@Deprecated` - Added `since` attribute - Added `forRemoval` attribute ``` @Deprecated(since="9", forRemoval=true) ``` --- # New deprecations - Applet API - `Observer` and `Observable` - boxed primitive constructors - `Object.finalize` - `java.security.acl` API - `com.sun.jarsigner` package - `policytool` --- # Stuff to be gone - CORBA - `sun.misc.Unsafe.defineClass` - pre 1.2 `SecurityManager` methods - `java.activation` - `java.se.ee` - `java.transaction` (subset of JTA to support CORBA interoperation) - `java.xml.bind` - `java.xml.ws` - `java.xml.ws.annotation` --- # Stuff gone in 9 - `_` as identifier - `hprof` and `jhat` tools - Demos and Samples --- class: center, middle # In other `new`s --- # Streams ## `Stream` (and primitive streams) now have - `takeWhile(Predicate)` - `dropWhile(Predicate`) ``` //Expected 0,1,2,3,4 IntStream.of(0,1,2,3,4,5,6,7,8,9).takeWhile(i -> i < 5).forEach(System.out::println) ``` ``` //Expected 5,6,7,8,9 IntStream.of(0,1,2,3,4,5,6,7,8,9).dropWhile(i -> i < 5).forEach(System.out::println) ``` --- # Multi-release JARs ``` jar root - A.class - B.class - C.class - D.class - META-INF - versions - 9 - A.class - B.class - 10 - A.class ``` --- # Private methods in interfaces ``` interface Greeter { ... default void greetSomeone(String personName, boolean female) { System.out.println("Hi " + getTitle(female) + " " + personName); } default void farewellSomeone(String personName, boolean female) { System.out.println("Bye " + getTitle(female) + " " + personName); } * private String getTitle(boolean female) { return female ? "Ms" : "Mr"; } } ``` --- # Finally - Process import statements correctly - `javac --release N` (no more source and target versions, `rt.jar` etc) - `Flow` class (with `Publisher`, `Subscriber`, `Processor`, `Subscription` for reactive streams) - HTML5 JavaDoc (with search) - UDP security (DTLS) - UTF-8 property files and Unicode 7.0 support - New version string schema for all JDK `$MAJOR.$MINOR.$SECURITY.$PATCH` --- class: center, middle, inverse background-image: url(bekklogo-white.png) background-position: center 20px background-repeat: no-repeat background-size: 250px # Thanks! ## @jfweden ## janwe.github.io/java9-presentation/ ## github.com/janwe/java9-presentation --- class: center, middle # Resources and inspiration #### [JavaZone 2017: Java SE 9, and its hidden treasures walkthrough](https://2017.javazone.no/program/e7edc7c29e7e4a619aa2bcd5bd577f57) #### https://docs.oracle.com/javase/9/jshell/toc.htm #### http://openjdk.java.net/projects/jdk9/ #### http://www.oracle.com/technetwork/java/javase/9-deprecated-features-3745636.html #### https://docs.oracle.com/javase/9/docs/api/overview-summary.html #### https://dzone.com/articles/java-9-besides-modules #### https://dzone.com/articles/java-9-http-20