java8$ - oraclecopyright©$201 5,$oracle$and/or$its$affiliates.$all$rights$reserved.$$|$...
TRANSCRIPT
Java 8 In Depth
Aurelio Garcia-‐Ribeyro Director Java Product Management June 2015
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. |
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Safe Harbor Statement The following is intended to outline our general product direcPon. It is intended for informaPon purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or funcPonality, and should not be relied upon in making purchasing decisions. The development, release, and Pming of any features or funcPonality described for Oracle’s products remains at the sole discrePon of Oracle.
4
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Program Agenda
§ IntroducPons
§ Details on some of the features
§ Review of JDK 8 “What’s new” secPon in the release notes
§ QA
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Java 8 “One of the biggest updates ever to a major language” Andrew Binstock
Former Editor in Chief, Dr.Dobbs , now with Java Magazine
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Abridged Content List
§ Lambda Expressions § Default Methods § Method References
§ Date Time APIs -‐ JSR 310 § Type AnnotaPons § Compact Profiles § Nashorn Javascript Engine
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
AbstracPng over Behavior Collection<Person> people = ...; for (Person p : people){
if (p.getAge() > 18) ?? How do we remove this person ??? }
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
AbstracPng over Behavior Collection<Person> people = ...; Iterator<Person> it = people.iterator(); while (it.hasNext()) { Person p = it.next(); if (p.getAge() > 18) it.remove(); }
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
AbstracPng over Behavior interface Predicate<T> { boolean test(T t); } class Collections { public static<T> void removeIf(Collection<T> coll, Predicate<T> pred) { ... } }
The API Designer Could create methods in the collecPon
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Collection<Person> people = ...; Collections.removeIf(people, new Predicate<Person>() { public boolean test(Person p) { return p.getAge() > 18; } } });
AbstracPng over Behavior But the code to use the new method would be bloated
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Collection<Person> people = ...; Collections.removeIf(people, new Predicate<Person>() { public boolean test(Person p) { return p.getAge() > 18; } } });
AbstracPng over Behavior
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
AbstracPng over Behavior Collection<Person> people = ...; Collections.removeIf(people, p -> p.getAge() > 18);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Aggregate operaPons Collection<Person> people = ...; int highestWeight = 0; for (Person p : people) { if (p.getGender() == MALE) { int weight = p.getWeight(); highestWeight = max(highestWeight,weight); } }
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Parallelism Collection<Person> people = ...; int highestWeight = people.stream() .filter(p -> p.getGender() == MALE) .mapToInt(p -> p.getWeight()) .max();
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Parallelism
class MaxProblem { final List<Person> people; final int size; MaxProblem(List<Person> ps) { this.people = ps; size = ps.size(); } public int solveSequentially() { int max = 0; for (Person p : people) { if (p.getGender() == MALE) max = Math.max(max, p.getWeight()); } return max; } public MaxProblem subproblem(int start, int end) { return new MaxProblem(people.subList(start, end)); } }
class MaxFinder extends RecursiveAction { private final MaxProblem problem; int max; protected void compute() { if (problem.size < THRESHOLD) sum = problem.solveSequentially(); else { int m = problem.size / 2; MaxFinder left, right; left = new MaxFinder(problem.subproblem(0, m)) right = new MaxFinder(problem.subproblem(m, problem.size)); forkJoin(left, right); max = Math.max(left.max, right.max); } } } ForkJoinExecutor pool = new ForkJoinPool(nThreads); MaxFinder finder = new MaxFinder(problem); pool.invoke(finder);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Parallelism Collection<Person> people = ...; int highestWeight = people.stream() .filter(p -> p.getGender() == MALE) .mapToInt(p -> p.getWeight()) .max();
Collection<Person> people = ...; int highestWeight = people.parallelStream() .filter(p -> p.getGender() == MALE) .mapToInt(p -> p.getWeight()) .max();
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Abridged Content List
§ Lambda Expressions § Default Methods § Method References
§ Date Time APIs -‐ JSR 310 § Type AnnotaPons § Compact Profiles § Nashorn Javascript Engine
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Default methods Collection<Person> people = ...; int highestWeight = people.stream() ... interface Collection<T> { ... default Stream<T> stream() { ... } }
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
StaPc Methods In Interfaces
• Previously it was not possible to include staPc methods in an interface • StaPc methods, by definiPon, are not abstract
– @FunctionalInterface can have zero or more staPc methods
static <T> Predicate<T> isEqual(Object target) { return (null == target) ? Objects::isNull : object -> target.equals(object); }
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Method References
list.replaceAll(s -> s.toUpperCase());
list.replaceAll(String::toUpperCase);
list.sort(Comparator.comparing(p -> p.getName()));
list.sort(Comparator.comparing(Person::getName));
// using static import
list.sort(comparing(Person::getName));
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Summary
• Lambdas are funcPons • Java SE 8 defines new APIs using funcPonal interfaces • Default methods • Method references Lambdas make code read more like the problem statement. The resul6ng code is clear, concise, and easy to maintain and modify.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Tools for Java SE 8
• Quickly convert anonymous inner classes to lambdas
Lambda Expressions
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Tools for Java SE 8
• Easily convert from lambdas to method references
Method References
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Tools for Java SE 8
• Specify a scope for upgrading to Java 8 – All/current projects – Specific package – Specific class
• Run converters • Visually preview proposals for refactoring
Refactoring in Batch Mode
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Abridged Content List
§ Lambda Expressions § Default Methods § Method References
§ Date Time APIs -‐ JSR 310 § Type AnnotaPons § Compact Profiles § Nashorn Javascript Engine
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JDK 8 Java Time Features – JSR 310
• Replaces java.uPl.Date, Calendar, TimeZone, DateFormat • Fluent, Immutable, Thread Safe, Easy to use
• Strong typing with fit for purpose types • Easy to use formafng and parsing
• Interoperable with java.uPl.Calendar/Date • Extensible Units, Fields, and Chronologies • Supports Regional Calendars • Supported by JDBC, java.sql.Date/Time/Timestamp
• The essenPal ISO 8601 Calendar for global business
New Improved Date Time API
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Range of types l Date consists of year, month and day l Time-‐of-‐day consists of hour, minute, second
- LocalDate -‐ a date with no Pme and no Pme-‐zone - LocalTime -‐ a Pme with no date and no Pme-‐zone - LocalDateTime -‐ combines LocalDate and LocalTime
l Time-‐zones handled separately - ZonedDateTime -‐ closest class to java.uPl.Calendar
l Instantaneous points in Pme - Instant -‐ closest class to java.uPl.Date
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Range of types l Date consists of year, month and day l Time-‐of-‐day consists of hour, minute, second
- LocalDate -‐ a date with no Pme and no Pme-‐zone - LocalTime -‐ a Pme with no date and no Pme-‐zone - LocalDateTime -‐ combines LocalDate and LocalTime
l Time-‐zones handled separately - ZonedDateTime -‐ closest class to java.uPl.Calendar
l Instantaneous points in Pme - Instant -‐ closest class to java.uPl.Date
In JDK 8, you have to choose the correct date/Pme type
when designing an applicaPon!
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Local Date l Stores year-‐month-‐day
- 12th March 2014
l Use cases: birthdays, start/end dates, holiday dates
LocalDate current = LocalDate.now(); LocalDate date = LocalDate.of(2013,Month.SEPTEMBER,12); if (current.isAfter(date)) … String str = date.toString(); // 2013-09-12 boolean leap = date.isLeapYear(); int monthLen = date.lengthOfMonth();
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Local Time l Stores hour-‐minute-‐second-‐nanosecond
- 13:30 (1:30pm)
l Use cases: shop opening hours, alarm clock
LocalTime current = LocalTime.now(); LocalTime time = LocalTime.of(13,30); if (current.isAfter(time)) … String str = time.toString(); // 13:30 time = time.plusHours(4).minusMinutes(1).withNano(0); time = time.truncatedTo(ChronoUnit.SECONDS);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Local Date-‐Time l Stores LocalDate and LocalTime
- 12th September 2013 at 13:30
l Use case: local date-‐Pme a flight takes off
dt1 = LocalDateTime.now(); dt2 = LocalDateTime.of(2013,SEPTEMBER,12, 13,30); dt1 = dt1.plusDays(2).minusHours(1); dt1 = dt1.with(next(TUESDAY)); dt2.toString(); // 2013-09-12T13:30 dt2 = dt2.truncatedTo(MINUTES);
http://www.flickr.com/photos/estevesm/473866656/
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Instant l Stores nanoseconds from 1970-‐01-‐01Z l Closest equivalent to java.uPl.Date l Use case: Pmestamp in logging
instant1 = Instant.now(); instant2 = Instant.now(); if (instant1.isAfter(instant2)) { … }
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Time zones l World is divided into various Pme zones l Time in a locaPon defined by poli%cal rules l Rules change frequently and in complex ways
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Time zones l World is divided into various Pme zones l Time in a locaPon defined by poli%cal rules l Rules change frequently and in complex ways
If you can avoid Pme-‐zones your applicaPon will be simpler!
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Time zone design l Four classes manage Pme-‐zone complexity l ZoneId -‐ "Europe/Paris", as per java.util.TimeZone l ZoneOffset -‐ "-‐05:00", offset from UTC/Greenwich l ZoneRules -‐ behind the scenes class defining the rules l ZonedDateTime -‐ main date/Pme class with Pme-‐zones
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Zone gaps and overlaps l Spring Daylight Saving 'gap' l Autumn/Fall Daylight Saving 'overlap' l No excepPons are thrown, just does something sensible l CreaPon chooses summer Pme
// one day before DST ends (overlap of one hour) zone = ZoneId.of("Europe/London"); dt = ZonedDateTime.of(2010,OCTOBER,27, 1,30,0,0, zone); // dt = 2010-10-27 01:30 +01:00 dt = dt.plusDays(1); // dt = 2010-10-28 01:30 +01:00 // retains offset where possible dt = dt.plusHours(1); // dt = 2010-10-28 01:30 +00:00 // offset changes, same time
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Calendar systems l All main classes use "ISO" calendar system l Calendar system defined in ISO-‐8601 - current 'civil' calendar applied to all Pme - not historically accurate
l Other calendar systems also supported - not supported to the same degree as ISO - Hijrah, Japanese, Minguo, ThaiBuddhist in the JDK
l Only affect dates, not Pmes
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Amounts l Amount of Pme not Ped to the Pmeline l eg. 6 years l eg. 32.4 seconds
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
DuraPon l Time-‐based amount
- hours, minutes, seconds and nanoseconds - some support for 24-‐hour days
l Use cases: sport stopwatch, Pmeout
duration = Duration.ofHours(6); // PT6H duration = duration.multipliedBy(3); // PT18H duration = duration.plusMinutes(30); // PT18H30M dt = LocalDateTime.now(); dt = dt.plus(duration);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Period l Date-‐based amount
- years, months and days
l Use cases: length of pregnancy, length of holiday
period = Period.ofMonths(9); // P9M period = period.plusDays(6); // P9M6D dt = LocalDateTime.now(); dt = dt.plus(period); period = Period.between(startDate, endDate);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Summary l LocalDate 2010-12-03
l LocalTime 11:05:30
l LocalDateTime 2010-12-03T11:05:30
l ZonedDateTime 2010-12-03T11:05:30+01:00 Europe/Paris
l Instant 2576458258.266 seconds after 1970-01-01
l Duration PT30S (30 seconds)
l Period P1Y6M (1 year and 6 months)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Abridged Content List
§ Lambda Expressions § Default Methods § Method References
§ Date Time APIs -‐ JSR 310 § Type AnnotaPons § Compact Profiles § Nashorn Javascript Engine
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
AnnotaPons On Java Types
• Before JD 8 annotaPons could only be used on type declaraPons – Classes, methods, variable definiPons
• JDK 8 allows annotaPons in places where types are used – e.g. parameters
• Permits error detecPon by pluggable type checkers – e.g. null pointer errors, race condiPons, etc
public void process(@notnull List data) {…}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Small Things • RepeaPng annotaPons
MulPple annotaPons with the same type applied to a single program element
• No more apt tool and associated API – Complete the transiPon to the JSR 269 implementaPon
• DocTree API – Provide access to the syntacPc elements of a javadoc comment
• DocLint tool – Use DocTree API to idenPfy basic errors in javadoc comments
• Javadoc support in javax.tools – Invoke javadoc tools from API as well as command line/exec
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Abridged Content List
§ Lambda Expressions § Default Methods § Method References
§ Date Time APIs -‐ JSR 310 § Type AnnotaPons § Compact Profiles § Nashorn Javascript Engine
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
12 Mb 17 Mb 22 Mb 50 Mb
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Nashorn JavaScript Engine
• Lightweight, high-‐performance JavaScript engine – Integrated into JRE
• Use exisPng javax.script API • ECMAScript-‐262 EdiPon 5.1 language specificaPon compliance • New command-‐line tool, jjs to run JavaScript • InternaPonalised error messages and documentaPon
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Program Agenda
§ IntroducPons
§ Details on some of the features
§ Review of JDK 8 “What’s new” secPon in the release notes
§ QA
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
And deep breath!
Oracle ConfidenPal – Internal/Restricted/Highly Restricted 51
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JDK 8 Innova3on • Lambda aka Closures • Language Interop • Nashorn
Core Libraries • Parallel operaPons for core
collecPons APIs • Improvements in funcPonality • Improved type inference
General Goodness • JVM enhancements • No PermGen limitaPons • Performance improvements
Java for Everyone • Profiles for constrained devices • JSR 310-‐Date & Time APIs • Non-‐Gregorian calendars • Unicode 6.2 • ResourceBundle • BCP47 locale matching • GlobalizaPon & Accessibility
Tools • JSR 308-‐AnnotaPons on Java Type • NaPve app bundling • App Store Bundling tools • jdeps
Client • Deployment enhancements • JavaFX 8 • Public UI Control API • Java SE Embedded support • Enhanced HTML5 support • 3D shapes and avributes • PrinPng
Security • Limited doPrivilege • NSA Suite B algorithm support • SNI Server Side support • DSA updated to FIPS186-‐3 • AEAD JSSE CipherSuites
Enterprise • Mission Control • Flight Recorder • Usage Tracker • Advanced Management Console • MSI Enterprise JRE Installer
52
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Where did most of this informaPon come from
• Java SE 8—Language and Library Features, Brian Goetz • IntroducPon to Lambda Expressions, Stuart Marks • A New Date and Time API—JSR-‐310, Stephen Colebourne • Enhanced Metadata—AnnotaPons and Access to Parameter Names, Alex Buckley and Michael Ernst
• Nashorn: JavaScript on the JVM, Jim Laskey
Java 8 Launch Event
hvps://www.oracle.com/java8launch
Search for: Java 8 Launch
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Q & A
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |