This document discusses new features in Java 8 including stream API, lambdas, default methods, optional values, date and time API, stamped locks, concurrent adders, improved annotations, new file operations, overflow operations, and the Nashorn JavaScript engine. It provides code examples and explanations of how to use these new features in Java 8.
1. 10+ new features
you ought to know
using Java 8
Oleg Tsal-Tsalko
JavaDay Lviv 2015
2. 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. 3CONFIDENTIAL
• 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. 4CONFIDENTIAL
• 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
7. 7CONFIDENTIAL
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. 8CONFIDENTIAL
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. 9CONFIDENTIAL
#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. 10CONFIDENTIAL
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?
13. 13CONFIDENTIAL
• 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. 14CONFIDENTIAL
• 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. 15CONFIDENTIAL
#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. 16CONFIDENTIAL
• 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
18. 18CONFIDENTIAL
• 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. 19CONFIDENTIAL
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
21. 21CONFIDENTIAL
• 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. 22CONFIDENTIAL
• [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. 23CONFIDENTIAL
• 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. 24CONFIDENTIAL
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
27. 27CONFIDENTIAL
• 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…