SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Java 8
What could possibly go wrong?
Grzegorz Rozniecki (@xaerxess)
October 11, 2016
About me
@xaerxess
Important: Images used in this presentation (and the presentation itself) are free to use under Creative Commons Attribution
License.
Code (reviews) addict Open Source advocate
I’m a software engineer who enjoys learning and likes sharing his knowledge. Big GNU/Linux fan and Open
Source Software advocate. I’ve developed software in various languages, including Perl, JavaScript, Java, Python,
PHP and Lisp (and experimented with few others).
● Being a programmer is mostly reading
code, not writing
● You are not your code!
● Freedom is important
● You can read how libraries, languages,
even operating systems are built - and
learn!
● Contribute, it’s easy!
Who?
Why?
What?
Where?
What now?
WHO uses Java 8
Quick journey from 1995 to 2016
1.7
1.6
1.5
1.2-1.4
<=1.1
Java 8 adoption
Java versions as of March 2016
October 201427%
38%
64%
May 2015
March 2016
WHY Java 8
(rhetorical)
lambdas
streams
Date API
Optional
CompletableFuture
Allows functional programming!method references
WHY it’s important?
default methods
Programming styles
...?
Why he’s talking about…
Programming styles
Imperative Declarative Functional
The focus is on what
steps the computer
should take rather than
what the computer will
do (ex. C, C++, Java).
The focus is on what
the computer should
do rather than how it
should do it (ex. SQL).
A subset of declarative
languages that has
heavy focus on
recursion.
Streams
java.util.stream
Classes in the new java.util.stream package
provide a Stream API to support
functional-style operations on streams of
elements. The Stream API is integrated into
the Collections API, which enables bulk
operations on collections, such as sequential
or parallel map-reduce transformations.
● Sequential
● Parallel
● Unordered?
“
”
Parallel streams
Tasks in ForkJoinPool
into smaller pieces
split
new subtasks
fork
computed tasks
join
1 2 3 4
results from pieces
compose
Parallel
streams
List<Integer> primes = IntStream
.range(1, 1_000_000)
.parallel()
.filter(PrimesPrint::isPrime)
.collect(toList());
// how many threads is this using?
// how do I configure that?
Defaults
// see ForkJoinPool Javadoc
-Djava.util.concurrent.ForkJoinPool.common.parallelism=4
Parallel
streams
ForkJoinPool forkJoinPool = new ForkJoinPool(2);
forkJoinPool.submit(() ->
IntStream.range(1, 1_000_000).parallel()
.filter(PrimesPrint::isPrime)
.collect(toList())
).get();
Custom ForkJoinPool
WHAT should I
use?
Effective Java, Item 47: Know and use
your libraries
Libraries
jOOL / jOOλ StreamEx Javaslang
● Almost drop-in
replacement
(extension) of
Stream
● Only sequential
● SQL-like collectors
● Adds TupleN,
FunctionN
● More goodies than
in jOOL
● Also parallel and
primitive streams
● Even
MoreCollectors
● Adds TupleN,
FunctionN
● “Go functional”
● Fully functional
library for Java 8+
● Adds functional
collection library
● Adds TupleN,
FunctionN and
much more (vide
currying)
Problem
static final ImmutableList<String> DATA = ImmutableList.of("foo", "bar", "baz", "bazinga");
static final String[] ARRAY_DATA = DATA.stream().toArray(String[]::new);
static final Iterable<String> ITERABLE_DATA = DATA;
static final Iterator<String> ITERATOR_DATA = DATA.iterator(); // don't do this at home or work!
How create Stream?
DATA.stream();
Arrays.stream(ARRAY_DATA);
StreamSupport.stream(ITERABLE_DATA.spliterator(), false);
StreamSupport.stream(
Spliterators.spliteratorUnknownSize(ITERATOR_DATA, Spliterator.ORDERED),
false);
Solution - jOOL
static final ImmutableList<String> DATA = ImmutableList.of("foo", "bar", "baz", "bazinga");
static final String[] ARRAY_DATA = DATA.stream().toArray(String[]::new);
static final Iterable<String> ITERABLE_DATA = DATA;
static final Iterator<String> ITERATOR_DATA = DATA.iterator(); // don't do this at home or work!
How create Stream?
Seq.seq(DATA);
Seq.seq(ARRAY_DATA);
Seq.seq(ITERABLE_DATA);
Seq.seq(DATA);
Solution - jOOL (fixed)
static final ImmutableList<String> DATA = ImmutableList.of("foo", "bar", "baz", "bazinga");
static final String[] ARRAY_DATA = DATA.stream().toArray(String[]::new);
static final Iterable<String> ITERABLE_DATA = DATA;
static final Iterator<String> ITERATOR_DATA = DATA.iterator(); // don't do this at home or work!
How create Stream?
Seq.seq(DATA);
Seq.of(ARRAY_DATA);
Seq.seq(ITERABLE_DATA);
Seq.seq(DATA);
We checked exceptions!
Arrays.stream(dir.listFiles()).forEach(file -> {
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
// Ouch, my fingers hurt! All this typing!
});
...especially in streams
Arrays.stream(dir.listFiles())
.map(Unchecked.function(File::getCanonicalPath))
.forEach(System.out::println);
Libraries
On a high level: jOOλ
extends/wraps the Java
collections. Javaslang ships with
their own collections.
/ Lukas Eder, creator of jOOL
Which is the best?
I suspect, jOOλ is good for quick
wins, whereas Javaslang is a
strategic decision.
CompletableFuture
and CompletionStage
● ~50 methods
● Concept from JS promises
● What could go wrong?
Top tip
Remembering
CompletableFuture API
// CompletableFuture<T> future;
public interface Function<T, R> {
R apply(T t);
}
future.thenApply(function) // CompletableFuture<R>
public interface Consumer<T> {
void accept(T t);
}
future.thenAccept(consumer) // CompletableFuture<Void>
+ xxxAsync for custom Executor
Date API
java.time
The main API for dates, times, instants, and
durations. (...) They are based on the ISO
calendar system, which is the de facto world
calendar following the proleptic Gregorian
rules. All the classes are immutable and
thread-safe.
“
Dates and parsing
String value = "2001-08-22 03:04:05.321 America/Los_Angeles";
LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of(value.substring(23, value.length()).trim()))
.with(LocalDateTime.parse(value.substring(0, 23).trim(), TIMESTAMP));
System.out.println(localDateTime); // 2001-08-22T03:04:05.321
Custom format
Dates and parsing
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
private static final DateTimeFormatter TIMESTAMP_WITH_TIME_ZONE = new DateTimeFormatterBuilder()
.append(DATE)
.appendLiteral(' ')
.append(TIME)
.appendLiteral(' ')
.appendZoneId()
.toFormatter();
String value = "2001-08-22 03:04:05.321 America/Los_Angeles";
LocalDateTime localDateTime = LocalDateTime.parse(value, TIMESTAMP_WITH_TIME_ZONE);
System.out.println(localDateTime); // 2001-08-22T03:04:05.321
DateTimeFormatterBuilder
Dates and parsing
private static final DateTimeFormatter TIMESTAMP_WITH_TIME_ZONE = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendLiteral(' ')
.appendZoneId()
.toFormatter();
String value = "2001-08-22 03:04:05.321 America/Los_Angeles";
LocalDateTime localDateTime = LocalDateTime.parse(value, TIMESTAMP_WITH_TIME_ZONE);
System.out.println(localDateTime); // 2001-08-22T03:04:05.321
DateTimeFormatterBuilder
Duration
// shiny new Duration class!
long durationMillis = 1000L;
TimeUnit unit = TimeUnit.MILLISECONDS;
Duration duration = Duration.of(durationMillis, unit);
What’s wrong with these examples?
// so let's use proper units
Duration duration = Duration.of(2, ChronoUnit.MONTHS);
java.time.temporal.UnsupportedTemporalTypeException: Unit must not have an estimated duration
Optional
To be, or not to be… (aka avoiding null)
Sigh, why does everything related to
Optional have to take 300 messages?
”Brian Goetz (2013-10-23 on
lambda-libs-spec-experts)
“
Junior Developer taking advice before starting work on a
legacy project
http://classicprogrammerpaintings.com/
Optional
Problems
● OptionalResult
Naming is hard...
● Optional#getOrElseThrowNoSuchElementException()
Naming is hard… again.
● Implements Serializable?
Deliberately not.
● If / else on Optional?
Vide using .get().
● Optional#stream()
Use stream.flatMap(Optional::stream) instead of:
stream.filter(Optional::isPresent).map(Optional::get)
Optional
Rules
1. Never, ever, use null for an Optional variable or
return value.
2. Never use Optional.get() unless you can prove
that the Optional is present.
3. Prefer alternatives APIs over Optional.isPresent()
and Optional.get().
4. It’s generally a bad idea to create an Optional
for the specific purpose of chaining methods
from it to get a value.
5. If an Optional chain has a nested Optional chain,
or has an intermediate result of
Optional<Optional<T>>, it’s probably too
complex.
6. Avoid using Optional in fields, method
parameters, and collections.
7. Don’t use an Optional to wrap any collection
type (List, Set, Map). Instead, use an empty
collection to represent the absence of values.
WHERE should I
find answers?
Contribute!
That’s all
(questions?)
Thank you for your
participation!

Weitere ähnliche Inhalte

Was ist angesagt?

Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuningosa_ora
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With SpoonGérard Paligot
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8Garth Gilmour
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyondFabio Tiriticco
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8Dinesh Pathak
 
JProfiler8 @ OVIRT
JProfiler8 @ OVIRTJProfiler8 @ OVIRT
JProfiler8 @ OVIRTLiran Zelkha
 

Was ist angesagt? (20)

Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With Spoon
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Java8
Java8Java8
Java8
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
 
JProfiler8 @ OVIRT
JProfiler8 @ OVIRTJProfiler8 @ OVIRT
JProfiler8 @ OVIRT
 
Taking User Input in Java
Taking User Input in JavaTaking User Input in Java
Taking User Input in Java
 
Java 7 & 8
Java 7 & 8Java 7 & 8
Java 7 & 8
 

Andere mochten auch

JDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done Right
JDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done RightJDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done Right
JDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done RightPROIDEA
 
JDD 2016 - Tomasz Ducin - Backend-less Development Revisited
JDD 2016 - Tomasz Ducin - Backend-less Development RevisitedJDD 2016 - Tomasz Ducin - Backend-less Development Revisited
JDD 2016 - Tomasz Ducin - Backend-less Development RevisitedPROIDEA
 
2016 - Daniel Lebrero - REPL driven development
2016 - Daniel Lebrero - REPL driven development2016 - Daniel Lebrero - REPL driven development
2016 - Daniel Lebrero - REPL driven developmentPROIDEA
 
JDD 2016 - Christin Gorman - Concurrency in Java
JDD 2016 - Christin Gorman - Concurrency in JavaJDD 2016 - Christin Gorman - Concurrency in Java
JDD 2016 - Christin Gorman - Concurrency in JavaPROIDEA
 
JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?PROIDEA
 
JDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And Profit
JDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And ProfitJDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And Profit
JDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And ProfitPROIDEA
 
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...PROIDEA
 
JDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMH
JDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMHJDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMH
JDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMHPROIDEA
 

Andere mochten auch (8)

JDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done Right
JDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done RightJDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done Right
JDD 2016 - Grzegorz Piwowarek - Davaslang - Functional Java Done Right
 
JDD 2016 - Tomasz Ducin - Backend-less Development Revisited
JDD 2016 - Tomasz Ducin - Backend-less Development RevisitedJDD 2016 - Tomasz Ducin - Backend-less Development Revisited
JDD 2016 - Tomasz Ducin - Backend-less Development Revisited
 
2016 - Daniel Lebrero - REPL driven development
2016 - Daniel Lebrero - REPL driven development2016 - Daniel Lebrero - REPL driven development
2016 - Daniel Lebrero - REPL driven development
 
JDD 2016 - Christin Gorman - Concurrency in Java
JDD 2016 - Christin Gorman - Concurrency in JavaJDD 2016 - Christin Gorman - Concurrency in Java
JDD 2016 - Christin Gorman - Concurrency in Java
 
JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?
 
JDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And Profit
JDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And ProfitJDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And Profit
JDD 2016 - Pawel Szulc - Writing Your Wwn RDD For Fun And Profit
 
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
 
JDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMH
JDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMHJDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMH
JDD 2016 - Wojciech Oczkowski - Testowanie Wydajnosci Za Pomoca Narzedzia JMH
 

Ähnlich wie JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCFAKHRUN NISHA
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang YoonJesang Yoon
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETMaarten Balliauw
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsJarrod Overson
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play frameworkFelipe
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application FrameworkJady Yang
 
LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1Hajime Tazaki
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...NETFest
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarMaarten Balliauw
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 

Ähnlich wie JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong (20)

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Java
JavaJava
Java
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoon
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Java multi thread programming on cmp system
Java multi thread programming on cmp systemJava multi thread programming on cmp system
Java multi thread programming on cmp system
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 

Kürzlich hochgeladen

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Kürzlich hochgeladen (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong

  • 1. Java 8 What could possibly go wrong? Grzegorz Rozniecki (@xaerxess) October 11, 2016
  • 2. About me @xaerxess Important: Images used in this presentation (and the presentation itself) are free to use under Creative Commons Attribution License. Code (reviews) addict Open Source advocate I’m a software engineer who enjoys learning and likes sharing his knowledge. Big GNU/Linux fan and Open Source Software advocate. I’ve developed software in various languages, including Perl, JavaScript, Java, Python, PHP and Lisp (and experimented with few others). ● Being a programmer is mostly reading code, not writing ● You are not your code! ● Freedom is important ● You can read how libraries, languages, even operating systems are built - and learn! ● Contribute, it’s easy!
  • 4. WHO uses Java 8 Quick journey from 1995 to 2016
  • 6. Java 8 adoption Java versions as of March 2016 October 201427% 38% 64% May 2015 March 2016
  • 8. lambdas streams Date API Optional CompletableFuture Allows functional programming!method references WHY it’s important? default methods
  • 10. Programming styles Imperative Declarative Functional The focus is on what steps the computer should take rather than what the computer will do (ex. C, C++, Java). The focus is on what the computer should do rather than how it should do it (ex. SQL). A subset of declarative languages that has heavy focus on recursion.
  • 11. Streams java.util.stream Classes in the new java.util.stream package provide a Stream API to support functional-style operations on streams of elements. The Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map-reduce transformations. ● Sequential ● Parallel ● Unordered? “ ”
  • 12. Parallel streams Tasks in ForkJoinPool into smaller pieces split new subtasks fork computed tasks join 1 2 3 4 results from pieces compose
  • 13. Parallel streams List<Integer> primes = IntStream .range(1, 1_000_000) .parallel() .filter(PrimesPrint::isPrime) .collect(toList()); // how many threads is this using? // how do I configure that? Defaults // see ForkJoinPool Javadoc -Djava.util.concurrent.ForkJoinPool.common.parallelism=4
  • 14. Parallel streams ForkJoinPool forkJoinPool = new ForkJoinPool(2); forkJoinPool.submit(() -> IntStream.range(1, 1_000_000).parallel() .filter(PrimesPrint::isPrime) .collect(toList()) ).get(); Custom ForkJoinPool
  • 15. WHAT should I use? Effective Java, Item 47: Know and use your libraries
  • 16. Libraries jOOL / jOOλ StreamEx Javaslang ● Almost drop-in replacement (extension) of Stream ● Only sequential ● SQL-like collectors ● Adds TupleN, FunctionN ● More goodies than in jOOL ● Also parallel and primitive streams ● Even MoreCollectors ● Adds TupleN, FunctionN ● “Go functional” ● Fully functional library for Java 8+ ● Adds functional collection library ● Adds TupleN, FunctionN and much more (vide currying)
  • 17. Problem static final ImmutableList<String> DATA = ImmutableList.of("foo", "bar", "baz", "bazinga"); static final String[] ARRAY_DATA = DATA.stream().toArray(String[]::new); static final Iterable<String> ITERABLE_DATA = DATA; static final Iterator<String> ITERATOR_DATA = DATA.iterator(); // don't do this at home or work! How create Stream? DATA.stream(); Arrays.stream(ARRAY_DATA); StreamSupport.stream(ITERABLE_DATA.spliterator(), false); StreamSupport.stream( Spliterators.spliteratorUnknownSize(ITERATOR_DATA, Spliterator.ORDERED), false);
  • 18. Solution - jOOL static final ImmutableList<String> DATA = ImmutableList.of("foo", "bar", "baz", "bazinga"); static final String[] ARRAY_DATA = DATA.stream().toArray(String[]::new); static final Iterable<String> ITERABLE_DATA = DATA; static final Iterator<String> ITERATOR_DATA = DATA.iterator(); // don't do this at home or work! How create Stream? Seq.seq(DATA); Seq.seq(ARRAY_DATA); Seq.seq(ITERABLE_DATA); Seq.seq(DATA);
  • 19. Solution - jOOL (fixed) static final ImmutableList<String> DATA = ImmutableList.of("foo", "bar", "baz", "bazinga"); static final String[] ARRAY_DATA = DATA.stream().toArray(String[]::new); static final Iterable<String> ITERABLE_DATA = DATA; static final Iterator<String> ITERATOR_DATA = DATA.iterator(); // don't do this at home or work! How create Stream? Seq.seq(DATA); Seq.of(ARRAY_DATA); Seq.seq(ITERABLE_DATA); Seq.seq(DATA);
  • 20. We checked exceptions! Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); ...especially in streams Arrays.stream(dir.listFiles()) .map(Unchecked.function(File::getCanonicalPath)) .forEach(System.out::println);
  • 21. Libraries On a high level: jOOλ extends/wraps the Java collections. Javaslang ships with their own collections. / Lukas Eder, creator of jOOL Which is the best? I suspect, jOOλ is good for quick wins, whereas Javaslang is a strategic decision.
  • 22. CompletableFuture and CompletionStage ● ~50 methods ● Concept from JS promises ● What could go wrong?
  • 23. Top tip Remembering CompletableFuture API // CompletableFuture<T> future; public interface Function<T, R> { R apply(T t); } future.thenApply(function) // CompletableFuture<R> public interface Consumer<T> { void accept(T t); } future.thenAccept(consumer) // CompletableFuture<Void> + xxxAsync for custom Executor
  • 24. Date API java.time The main API for dates, times, instants, and durations. (...) They are based on the ISO calendar system, which is the de facto world calendar following the proleptic Gregorian rules. All the classes are immutable and thread-safe. “
  • 25. Dates and parsing String value = "2001-08-22 03:04:05.321 America/Los_Angeles"; LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of(value.substring(23, value.length()).trim())) .with(LocalDateTime.parse(value.substring(0, 23).trim(), TIMESTAMP)); System.out.println(localDateTime); // 2001-08-22T03:04:05.321 Custom format
  • 26. Dates and parsing private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); private static final DateTimeFormatter TIMESTAMP_WITH_TIME_ZONE = new DateTimeFormatterBuilder() .append(DATE) .appendLiteral(' ') .append(TIME) .appendLiteral(' ') .appendZoneId() .toFormatter(); String value = "2001-08-22 03:04:05.321 America/Los_Angeles"; LocalDateTime localDateTime = LocalDateTime.parse(value, TIMESTAMP_WITH_TIME_ZONE); System.out.println(localDateTime); // 2001-08-22T03:04:05.321 DateTimeFormatterBuilder
  • 27. Dates and parsing private static final DateTimeFormatter TIMESTAMP_WITH_TIME_ZONE = new DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_LOCAL_DATE) .appendLiteral(' ') .append(DateTimeFormatter.ISO_LOCAL_TIME) .appendLiteral(' ') .appendZoneId() .toFormatter(); String value = "2001-08-22 03:04:05.321 America/Los_Angeles"; LocalDateTime localDateTime = LocalDateTime.parse(value, TIMESTAMP_WITH_TIME_ZONE); System.out.println(localDateTime); // 2001-08-22T03:04:05.321 DateTimeFormatterBuilder
  • 28. Duration // shiny new Duration class! long durationMillis = 1000L; TimeUnit unit = TimeUnit.MILLISECONDS; Duration duration = Duration.of(durationMillis, unit); What’s wrong with these examples? // so let's use proper units Duration duration = Duration.of(2, ChronoUnit.MONTHS); java.time.temporal.UnsupportedTemporalTypeException: Unit must not have an estimated duration
  • 29. Optional To be, or not to be… (aka avoiding null) Sigh, why does everything related to Optional have to take 300 messages? ”Brian Goetz (2013-10-23 on lambda-libs-spec-experts) “ Junior Developer taking advice before starting work on a legacy project http://classicprogrammerpaintings.com/
  • 30. Optional Problems ● OptionalResult Naming is hard... ● Optional#getOrElseThrowNoSuchElementException() Naming is hard… again. ● Implements Serializable? Deliberately not. ● If / else on Optional? Vide using .get(). ● Optional#stream() Use stream.flatMap(Optional::stream) instead of: stream.filter(Optional::isPresent).map(Optional::get)
  • 31. Optional Rules 1. Never, ever, use null for an Optional variable or return value. 2. Never use Optional.get() unless you can prove that the Optional is present. 3. Prefer alternatives APIs over Optional.isPresent() and Optional.get(). 4. It’s generally a bad idea to create an Optional for the specific purpose of chaining methods from it to get a value. 5. If an Optional chain has a nested Optional chain, or has an intermediate result of Optional<Optional<T>>, it’s probably too complex. 6. Avoid using Optional in fields, method parameters, and collections. 7. Don’t use an Optional to wrap any collection type (List, Set, Map). Instead, use an empty collection to represent the absence of values.
  • 32. WHERE should I find answers? Contribute!
  • 33. That’s all (questions?) Thank you for your participation!