Java 8 features

29
10+ new features you ought to know using Java 8 Oleg Tsal-Tsalko JavaDay Lviv 2015

Transcript of Java 8 features

10+ new features you ought to know using Java 8

Oleg Tsal-Tsalko

JavaDay Lviv 2015

LEAD SOFTWARE ENGINEER AT EPAM SYSTEMS. PATIONATE DEVELOPER, SPEAKER, ACTIVE MEMBER OF KIEV JUG. PARTICIPATE IN DIFFERENT EDUCATIONAL INITIATIVES, ENGINEERING EVENTS AND JCP/ADOPTJSR PROGRAMS.

OLEG TSAL-TSALKO

ABOUT ME

3 CONFIDENTIAL

•  Stream API •  Lambdas and method references •  Default methods •  Optional values •  Date & Time API •  Stamped Locks and Concurrent Adders •  Type annotations and repeated annotations •  New files operations •  Overflow operations and Base64 encoding •  Nashorn JavaScript engine

Agenda

4 CONFIDENTIAL

•  An abstraction that supports bulk operations over sequence of elements

•  Not a data structure •  Simple and logical chaining of operations •  Lazy evaluation •  Internal parallelism if required •  Concept of functional programming in Java

#1 Stream API

5 CONFIDENTIAL

•  Collection.stream() •  IntStream.range() •  Stream.of() •  Arrays.stream() •  BufferedReader.lines() •  CharSequence.chars() •  Pattern.splitAsStream()

How can I get a Stream?

6 CONFIDENTIAL

Fluent and simple

txns.stream() .filter(t ->t.getBuyer().getAge()>=65) .map(Txn::getSeller) .distinct() .sort(comparing(Seller::getName)) .forEach(s -> System.out.println(s.getName());

7 CONFIDENTIAL

java.util.function Package: Predicate<T>

Determine if the input of type T matches some criteria Consumer<T>

Accept a single input argument of type T, and return no result Function<T, R>

Apply a function to the input type T, generating a result of type R java.util.stream Package: Collector<T, A, R>

Used to collect stream of elements of type T into single result of type R

Collectors Contains number of predefined Collectors

Functional interfaces

8 CONFIDENTIAL

A lambda expression is an anonymous function –  Argument list, a return type, and a body (Object o) -> o.toString() –  Method reference Object::toString –  Capture value from enclosing context (Person p) ->p.getName().equals(name) –  Type inference p -> p.getName().equals(name) –  Forget to use anonymous classes You can now pass behavior as a data between your objects

#2 Lambdas

9 CONFIDENTIAL

#3 Method reference

FileFilter x = (File f) -> f.canRead();

FileFilter x = File::canRead;

FileFilter x = new FileFilter() { public boolean accept(File f) { return f.canRead(); } };

10 CONFIDENTIAL

Since Java doesn’t have Function type on it’s own Lambda’s type evaluated to some Functional interface: Runnable r = () -> { doSmth(); }; Callable c = () -> calcResult(); Comparator comp = (o1, o2) -> compare(o1, o2);

What’s your type?

11 CONFIDENTIAL

Influence on existing classes

java.lang.Iterable#forEach() java.util.Collection#stream() java.util.Collection#parallelStream() java.util.Comparator#comparing(…) java.util.Comparator#thenComparing(…) java.util.Comparator#reverse() …

12 CONFIDENTIAL

SHOW ME THE CODE

Lambdas and streams

TALK IS CHEAP

13 CONFIDENTIAL

•  Libraries need to evolve, or they stagnate •  Java preserves compatibility •  Multiple inheritance in Java? •  Default methods can reduce implementation

burden •  Resolution rules: – Class wins over interface – More specific subclass wins – No 3rd rule

#4 Default methods

14 CONFIDENTIAL

•  Annoyed by NPEs? •  Should your method return null or throw

RuntimeException? •  Wondering how to implement SpecialCase

pattern? •  Inspired by functional programming and want to

build a method chain for NULL handling? => You are lucky with Java 8…

#5 Optional

15 CONFIDENTIAL

#6 Date & Time API

•  Replaces old ambiguous java.util.Date, Calendar, TimeZone, DateFormat classes

with lots of deprecations •  More fluent/simple/clean API •  Immutable classes •  Using Java8 features including lambdas •  Precise separation of concepts

16 CONFIDENTIAL

•  LocalDate – a date only •  LocalTime – a time only •  LocalDateTime – date with time •  ZonedDateTime – date with time in time zone •  Period - date-based amount of time •  Duration - time-based amount of time •  And more…

Range of types

17 CONFIDENTIAL

Time Zones

If you can avoid using TimeZones – do it! If not – use ZonedDateAndTime!

18 CONFIDENTIAL

•  ZoneId – replacement for TimeZone class (e.g. “Europe/London”, “Europe/Kiev”)

•  ZoneOffset – representing offset from UTC time •  ZoneRules – behind the scenes class which

defines time zone rules •  ZonedDateTime – main date/time class which is

aware of time zones

TimeZone classes in Java 8

19 CONFIDENTIAL

New API is very flexible because it based on number of abstractions at it’s bottom: Temporal – parent class for all date/time objects which defines mutation operation for them such as plus/minus/with TemporalAdjuster – functional interface which responsible for mutating Temporal objects TemporalField – represents parts/fields of date/time objects such as (DAY_OF_WEEK, MONTH, etc.) TemporalUnit – represents type of date/time values such as (MINUTES, DAYS, YEARS, etc.) TemporalAmount – class which represents amount of time

Power of abstraction

20 CONFIDENTIAL

SHOW ME THE CODE

Optional and Date and Time API

TALK IS CHEAP

21 CONFIDENTIAL

•  Whenever we think of using RWLock •  RWLock can cause starvation of readers •  RWLock is pessimistic on reads

•  Read lock is optimistic •  Optimistic lock can be converted to pessimistic

lock if necessary •  Write locks are always pessimistic

#7 StampedLock

22 CONFIDENTIAL

•  [Java 5] When readers are given priority, then writers might never be able to complete •  [Java 6] But when writers are given

priority, readers might be starved ⇒ In Java 8 use StampedLock instead!

RWLock starvation

23 CONFIDENTIAL

•  Pros – Has much better performance than

ReentrantReadWriteLock – Latest versions do not suffer from starvation

of writers •  Cons –  Idioms are more difficult to get right than

with ReadWriteLock – A small difference can make a big difference

in performance

StampedLock

24 CONFIDENTIAL

How would you implement counter in multithreaded environment? •  Dirty counters (silly) •  Synchronized (very slow) •  RWLock (slow) •  Volatile (only if you have 1 writer/updater) •  AtomicInteger (yes, before Java 8…)

⇒  LongAdder in Java 8!

#8 Concurrent Adders

25 CONFIDENTIAL

WANT MORE?

26 CONFIDENTIAL

9 Improved annotations

10 New file operations

11 Overflow operations

12 Base64 encoding

13 Nashorn JavaScript engine

27 CONFIDENTIAL

•  Process Termination •  Strong Random Generation •  Date.toInstant() •  Interface static methods •  Better Type Inference •  Parameter names support by compiler •  Parallel Arrays •  Nashorn CLI JavaScript interpriter •  Class dependency analyzer

However there are even more…

28 CONFIDENTIAL

•  https://www.google.com/?gws_rd=ssl •  https://github.com/RichardWarburton/java-8-

lambdas-exercises •  http://javaspecialists.eu/talks/jfokus13/

PhaserAndStampedLock.pdf •  http://www.javacodegeeks.com/2014/05/

java-8-features-tutorial.html •  http://blog.takipi.com/10-features-in-java-8-

you-havent-heard-of/

Resources

29 CONFIDENTIAL

QUESTIONS?

Skype: oleg.tsalko Twitter: @tsaltsol

THANK YOU