SlideShare a Scribd company logo
Java 8
Interesting parts

Vaidas Pilkauskas, Kasparas Rudokas
Vilnius JUG
Agenda
●   Lambda
●   Date & Time
●   PermGen
●   Annotations
Lambda
JSR 335
lambda vs. closure
A lambda is just an anonymous function.

myCollection.filter(e ‑> e.length() >= 5)


A closure is any function which closes over the environment in which it was
defined. This means that it can access variables not in its parameter list.

int minLength = 5;
myCollection.filter(new Predicate(){
   boolean apply(MyElement e) {
     return e != null ? e.length >= minLength : false;
   }
})
Project Lambda (JSR 335)
● Language changes
  ○ Lambda Expression
  ○ Virtual Extension Method
● Library changes
  ○ Functional API
  ○ Parallel collections
  ○ Bulk Operations
Problem
String[] names = {"Alice", "Bob", "Charlie", Dave"};
Arrays.sort(names, new Comparator<String>() {
  @Override
  public int compare(String o1, String o2) {
    return o1.compareToIgnoreCase(o2);
  }
});
"tiny" anonymous inner
class
String[] names = {"Alice", "Bob", "Charlie", Dave"};
Arrays.sort(names, new Comparator<String>() {
  @Override
  public int compare(String o1, String o2) {
    return o1.compareToIgnoreCase(o2);
  }
});
"tiny" and useful
●   callbacks
●   runnables
●   event handlers
●   comparators
●   ...and many other cases
All we need!
String[] names = {"Alice", "Bob", "Charlie", Dave"};
Arrays.sort(names, new Comparator<String>() {
  @Override
  public int compare(String o1, String o2) {
    return o1.compareToIgnoreCase(o2);
  }
});
Solution - closure
String[] names = {"Alice", "Bob", "Charlie", Dave"};
Arrays.sort(names, (o1, o2) -> o1.compareToIgnoreCase(o2));
What do we mean by
 closures?
● a unit of deferred execution
● code that can be passed as a value
● can be used in an assignment
  statement
● capture of a surrounding environment
Lambda Expressions
s -> s.length()
(int x, int y) -> x+y
() -> 42

(x, y, z) -> {
  if (x == y) return x;
  else {
    int result = y;
    for (int i = 1; i < z; i++)
      result *= i;
    return result;
  }
}
Lambda Syntax
principally because something similar
has been generally well-received in
other Java-like languages (C# and
Scala), and a clearly "better" alternative
did not present itself
Lambda
● Effectively final variables
Lambda
● Effectively final variables
● Shadowing
Lambda
● Effectively final variables
● Shadowing
● break, continue must be local
Lambda
●   Effectively final variables
●   Shadowing
●   break, continue must be local
●   this - lambda is not an instance
    method. (this == surrounding context
    object)
Lambda
● Effectively final variables
● Shadowing
● break, continue must be local
● this - lambda is not an instance
  method. (this == surrounding context
  object)
● throw completes method abruptly
Functional Interfaces
A functional interface is an interface
that has just one abstract method, and
thus represents a single function
contract.
Functional Interfaces
SAM - Single Abstract Method interfaces
one method excluding Object methods
interface Runnable { void run(); }   // Functional

interface Foo { boolean equals(Object obj); }
 // Not functional; equals is already an implicit member

interface Comparator<T> {
  boolean equals(Object obj);
  int compare(T o1, T o2);
}
// Functional; Comparator has one abstract non-Object method
Method References
Method reference is a shorthand for a lambda invoking just
that method

System::getProperty
"abc"::length
String::length
super::toString
ArrayList::new

Arrays.sort(ints, Integer::compareTo);
Method References
Static methods simply translate like lambda with same
arguments and return type

class Math {
  public static int max(int a, int b) {...}
}
interface Operator<T> {
  T eval(T left, T right);
}
Operator<Integer> lambda = (a, b) -> Math.max(a, b);
Operator<Integer> methodRef = Math::max;
Method References
Non static method reference of type T translates like
lambda with an additional argument of type T

Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase
(s2);

//translates to:
Comparator<String> c = String::compareToIgnoreCase;
Method References
Instance method reference translates like lambda with same
arguments and return type (and implicit receiver)

Callable<Integer> l = () -> "boo".length();
//translates to:
Callable<Integer> c = "boo"::length;
Method References
String[] names = {"Alice", "Bob", "Charlie", Dave"};
Arrays.sort(names,
            (o1, o2) -> o1.compareToIgnoreCase(o2));

//translates to

String[] names = {"Alice", "Bob", "Charlie", Dave"};
Arrays.sort(names, String::compareToIgnoreCase);
Compatibility
           Cannot add new interface methods
(without forcing current interface users to implement them)

      But we need new lambda enabled methods
               (on Java core libraries!)
Default methods
 (also known as)
● virtual extension methods
● defender methods
Default methods
interface NormalInterface {
  void myNormalMethod();
  void myDefaultMethod () default {
    System.out.println("-> myDefaultMethod");
  }
}

class NormalInterfaceImpl implements NormalInterface {
  @Override
  public void myNormalMethod() {
    System.out.println("-> myNormalMethod");
  }
}
Functional Collections
Major changes in collection API:
● Internal iteration support with Iterable/Stream interfaces
   (forEach, filter, map, etc)
Functional Collections
Major changes in collection API:
● Internal iteration support with Iterable/Stream interfaces
   (forEach, filter, map, etc)
● Explicit parallel APIs for greater parallelism support.
   These can be combined with Fork/Join to divide the
   tasks
Functional Collections
Major changes in collection API:
● Internal iteration support with Iterable/Stream interfaces
   (forEach, filter, map, etc)
● Explicit parallel APIs for greater parallelism support.
   These can be combined with Fork/Join to divide the
   tasks
● Greater stress on immutability and avoiding in-place
   mutation which was done in the conventional for-each
   loops
Example
String[] names = {"Alice", "Bob", "Charlie", "Dave"};

List<String> filteredNames = Streams.stream(names)
                .filter(e -> e.length() >= 4)
                .into(new ArrayList<>());

filteredNames.stream().forEach(System.out::println);
Streams
● No storage - nothing is stored in stream
Streams
● No storage - nothing is stored in stream
● Functional in nature - new values are produced
Streams
● No storage - nothing is stored in stream
● Functional in nature - new values are produced
● Laziness-seeking. Many operations can be
   implemented lazily
Streams
● No storage - nothing is stored in stream
● Functional in nature - new values are produced
● Laziness-seeking. Many operations can be
    implemented lazily
●   Bounds optional. Think of infinite stream
Functional interfaces
java.util.functions
● Predicate - a property of the object passed as
   argument
● Block - an action to be performed with the object
   passed as argument
● Mapper - transform a T to a U
● ...
Parallelism
//sequential
int sum = myCollection.stream()
                .filter(b -> b.getColor() == BLUE)
                .map(b -> b.getWeight())
                .sum();
//parallel
int sum = myCollection.parallel()
                .filter(b -> b.getColor() == BLUE)
                .map(b -> b.getWeight())
                .sum();
Advantages
● Elements may be computed lazily. If we apply a Mapper
  to a collection of a thousand elements but only iterate
  over the first three, the remaining elements will never be
  mapped.
Advantages
● Elements may be computed lazily. If we apply a Mapper
  to a collection of a thousand elements but only iterate
  over the first three, the remaining elements will never be
  mapped.
● Method chaining is encouraged. Hence there's no need
  to store intermediate results in their own collections.
Advantages
● Elements may be computed lazily. If we apply a Mapper
  to a collection of a thousand elements but only iterate
  over the first three, the remaining elements will never be
  mapped.
● Method chaining is encouraged. Hence there's no need
  to store intermediate results in their own collections.
● Internal iteration hides implementation decisions. For
  example, we could parallelize a map() operation just by
  writing myCollection.parallel().map(e ‑> e.length()).
Try it out today!
The prototype compiler is being implemented in OpenJDK.
● Source code is available at http://hg.openjdk.java.
   net/lambda/lambda
● Binary snapshots of the lambda-enabled JDK prototype
   are available athttp://jdk8.java.net/lambda
IDE support:
 ● Netbeans 8 Nightly Builds with experimental Lambda
   support
 ● IDEA 12 EAP with experimental Lambda support
Date & Time API
JSR 310
Oldies: Date
● Mutable
Oldies: Date
● Mutable
● Years being indexed from 1900
Oldies: Date
● Mutable
● Years being indexed from 1900
● Months being indexed from 0
Oldies: Date
● Mutable
● Years being indexed from 1900
● Months being indexed from 0

Ex.:
  Date d = new Date(1L);
  System.out.println(d.toString());
Oldies: Date
● Mutable
● Years being indexed from 1900
● Months being indexed from 0

Ex.:
  Date d = new Date(1L);
  System.out.println(d.toString());
  //Thu Jan 01 02:00:00 EET 1970
Oldies: Calendar
● Mutable
Oldies: Calendar
● Mutable
● Not very convenient (lack of simple field
  methods)
Oldies: Calendar
● Mutable
● Not very convenient (lack of simple field
  methods)
● Very difficult to extend (add new calendars)
Oldies: Calendar
● Mutable
● Not very convenient (lack of simple field
  methods)
● Very difficult to extend (add new calendars)

Ex.:
  Calendar c = Calendar.getInstance();
  int weekday = c.get(DAY_OF_WEEK);
Oldies: Calendar
● Mutable
● Not very convenient (lack of simple field
  methods)
● Very difficult to extend (add new calendars)

Ex.:
  Calendar c = Calendar.getInstance();
  int weekday = c.get(DAY_OF_WEEK);
  Date d = c.getTime();
Under pressure...
JSR 310
● Immutable
JSR 310
● Immutable
● Defines consistent language for domain
  ○ Offset from UTC vs TimeZone
  ○ Machine vs Human
  ○ ISO 8601
JSR 310
● Immutable
● Defines consistent language for domain
  ○ Offset from UTC vs TimeZone
  ○ Machine vs Human
  ○ ISO 8601
● No old Date/Calendar usage (clean)
JSR 310
● Immutable
● Defines consistent language for domain
  ○ Offset from UTC vs TimeZone
  ○ Machine vs Human
  ○ ISO 8601
● No old Date/Calendar usage (clean)
● Extensible
JSR 310
● Immutable
● Defines consistent language for domain
  ○ Offset from UTC vs TimeZone
  ○ Machine vs Human
  ○ ISO 8601
● No old Date/Calendar usage (clean)
● Extensible
● Led by JodaTime creator (S. Colebourne)
Example: JSR 310
Clock clock = Clock.systemUTC();
LocalDate localDate = LocalDate.now(clock);
//2012-11-13
Example: JSR 310
Clock clock = Clock.systemUTC();
LocalDate localDate = LocalDate.now(clock);
//2012-11-13

MonthDay brasilBday = MonthDay.of(JUNE, 21);
Example: JSR 310
Clock clock = Clock.systemUTC();
LocalDate localDate = LocalDate.now(clock);
//2012-11-13

MonthDay brasilBday = MonthDay.of(JUNE, 21);

ZoneId zoneId = ZoneId.of("America/New_York");
Clock clock = Clock.system(zoneId);
ZonedDateTime zonedDateTimeUS = ZonedDateTime.now(clock);
//2012-11-11T04:17:58.693-05:00[America/New_York]
Example: JSR 310
import static javax.time.calendrical.LocalPeriodUnit.
HOURS;

Period p = Period.of(5, HOURS);
LocalTime time = LocalTime.now();
LocalTime newTime;
newTime = time.plus(5, HOURS);
// or
newTime = time.plusHours(5);
// or
newTime = time.plus(p);
Why not Joda Time?
●   Machine timelines
●   Pluggable chronology
●   Nulls
●   Internal implementation
VM/GC
JEP 122 & JEP 156
PermGen removal
● Java Heap vs PermGen
PermGen removal
● Java Heap vs PermGen
PermGen removal
● Java Heap vs PermGen




● Why it was required anyway?
PermGen removal
● Java Heap vs PermGen




● Why it was required anyway?
● So what?
Annotations
JSR 308 & JEP 120
Type Annotations
● In Java 7 we have annotations on
  declarations

Ex.:
  class SomeClass { … }
  class ListElement<E> { … }
  public void v() (int I) {
      long l;
  {
Type Annotations
● JSR-308 brings annotations on Type use
● Are an enabler for the checkers framework

Ex.:
   new @Interned MyObject();
   myString = (@NonNull String) myObject;
   void monitorTemperature() throws
      @Critical TemperatureException { ... }
Repeating Annotations
● Before
  @Schedules ({
      @Schedule(dayOfMonth="Last"),
      @Schedule(dayOfWeek="Fri", hour="23")
  ({
  public void doPeriodicCleanup() { ... }
Repeating Annotations
● Before
  @Schedules ({
      @Schedule(dayOfMonth="Last"),
      @Schedule(dayOfWeek="Fri", hour="23")
  ({
  public void doPeriodicCleanup() { ... }


● After
  @Schedule(dayOfMonth="Last”)
  @Schedule(dayOfWeek="Fri", hour="23")
  public void doPeriodicCleanup() { ... }
Q&A
References
* Lambda
http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda
http://openjdk.java.net/projects/lambda/
http://jcp.org/aboutJava/communityprocess/edr/jsr335/index2.html
http://vimeo.com/48577033 (slides: http://www.slideshare.net/tkowalcz/java-gets-a-closure)
http://datumedge.blogspot.co.uk/2012/06/java-8-lambdas.html
http://www.theserverside.com/news/thread.tss?thread_id=68718
http://medianetwork.oracle.com/video/player/1785479333001
https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=6080
https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=5089
http://www.lektorium.tv/lecture/?id=14048
http://www.lektorium.tv/lecture/?id=14049
http://blog.xebia.com/2012/11/05/report-will-java-8s-lambda-change-the-face-of-the-world/
http://www.slideshare.net/fsarradin/java-8-lambda
http://programmers.stackexchange.com/questions/173441/what-triggered-the-popularity-of-lambda-functions-in-modern-mainstream-programmi?newsletter=1&nlcode=29983%
7c903a
http://www.slideshare.net/bje/java-closures
* Collections
http://www.javabeat.net/2012/05/enhanced-collections-api-in-java-8-supports-lambda-expressions/
http://cr.openjdk.java.net/~briangoetz/lambda/collections-overview.html
http://architects.dzone.com/articles/java-collections-api
References
* Remove the Permanent Generation
http://www.cubrid.org/blog/dev-platform/understanding-jvm-internals/
http://javaeesupportpatterns.blogspot.com/2011/10/java-7-features-permgen-removal.html
http://java.dzone.com/articles/busting-permgen-myths
https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=5135
* JSR 310: Date and Time API
http://java.dzone.com/articles/introducing-new-date-and-time
http://sourceforge.net/apps/mediawiki/threeten/index.php?title=ThreeTen
http://www.infoq.com/news/2010/03/jsr-310
https://docs.google.com/document/pub?id=1rd8yplQZIRz3LxMzpVLuskr1b0HwBmK9PXpdgBYojSw
http://sourceforge.net/apps/mediawiki/threeten/index.php?title=User_Guide
https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=4350
* General Java8
http://openjdk.java.net/projects/jdk8/features
http://www.pcadvisor.co.uk/news/software/3401314/oracle-java-upgrades-still-worthwhile-despite-postponed-features/
http://dhruba.name/2011/07/06/oracle-discusses-java-7-8-new-features-on-video/
http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2012/Java-8
http://www.parleys.com/#st=5&id=2850&sl=1
http://www.parleys.com/#st=5&id=2847
https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=2872
https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=10458
References
*Annotations
https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=4469
https://blogs.oracle.com/abuckley/entry/jsr_308_moves_forward
http://jcp.org/en/jsr/detail?id=308
http://openjdk.java.net/jeps/120
http://types.cs.washington.edu/checker-framework/

More Related Content

What's hot (20)

Introduction to Programming in LISP
Introduction to Programming in LISPIntroduction to Programming in LISP
Introduction to Programming in LISP
Knoldus Inc.
 
Lisp
LispLisp
Lisp
huzaifa ramzan
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
Roberto Casadei
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Advance Scala - Oleg Mürk
Advance Scala - Oleg MürkAdvance Scala - Oleg Mürk
Advance Scala - Oleg Mürk
Planet OS
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
MD Sayem Ahmed
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
Angelo Corsaro
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Scala
ScalaScala
Scala
Zhiwen Guo
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Alexey (Mr_Mig) Migutsky
 
Google06
Google06Google06
Google06
Zhiwen Guo
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
Java8
Java8Java8
Java8
Sunil Kumar
 
Introduction to Programming in LISP
Introduction to Programming in LISPIntroduction to Programming in LISP
Introduction to Programming in LISP
Knoldus Inc.
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
Roberto Casadei
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Advance Scala - Oleg Mürk
Advance Scala - Oleg MürkAdvance Scala - Oleg Mürk
Advance Scala - Oleg Mürk
Planet OS
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
MD Sayem Ahmed
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
Angelo Corsaro
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 

Similar to Java 8 (20)

Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
Mohsen Zainalpour
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Unit-3.pptx.pdf java api knowledge apiii
Unit-3.pptx.pdf java api knowledge apiiiUnit-3.pptx.pdf java api knowledge apiii
Unit-3.pptx.pdf java api knowledge apiii
mpfbaa
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
Java8
Java8Java8
Java8
Felipe Mamud
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Java 8
Java 8Java 8
Java 8
Sudipta K Paik
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
AkashSingh728626
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
Sergii Maliarov
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
Son Nguyen
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
x1 ichi
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Unit-3.pptx.pdf java api knowledge apiii
Unit-3.pptx.pdf java api knowledge apiiiUnit-3.pptx.pdf java api knowledge apiii
Unit-3.pptx.pdf java api knowledge apiii
mpfbaa
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
Sergii Maliarov
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
Son Nguyen
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
x1 ichi
 

More from vilniusjug (6)

Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
vilniusjug
 
QCon 2014 London (Vadim Platanov)
QCon 2014 London (Vadim Platanov)QCon 2014 London (Vadim Platanov)
QCon 2014 London (Vadim Platanov)
vilniusjug
 
Java 8 Date/Time API (Lithuanian)
Java 8 Date/Time API (Lithuanian)Java 8 Date/Time API (Lithuanian)
Java 8 Date/Time API (Lithuanian)
vilniusjug
 
Vilnius Java User Group 20 - IntelliJ IDEA
Vilnius Java User Group 20 - IntelliJ IDEAVilnius Java User Group 20 - IntelliJ IDEA
Vilnius Java User Group 20 - IntelliJ IDEA
vilniusjug
 
Vilnius Java User Group Meeting #13
Vilnius Java User Group Meeting #13Vilnius Java User Group Meeting #13
Vilnius Java User Group Meeting #13
vilniusjug
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
vilniusjug
 
QCon 2014 London (Vadim Platanov)
QCon 2014 London (Vadim Platanov)QCon 2014 London (Vadim Platanov)
QCon 2014 London (Vadim Platanov)
vilniusjug
 
Java 8 Date/Time API (Lithuanian)
Java 8 Date/Time API (Lithuanian)Java 8 Date/Time API (Lithuanian)
Java 8 Date/Time API (Lithuanian)
vilniusjug
 
Vilnius Java User Group 20 - IntelliJ IDEA
Vilnius Java User Group 20 - IntelliJ IDEAVilnius Java User Group 20 - IntelliJ IDEA
Vilnius Java User Group 20 - IntelliJ IDEA
vilniusjug
 
Vilnius Java User Group Meeting #13
Vilnius Java User Group Meeting #13Vilnius Java User Group Meeting #13
Vilnius Java User Group Meeting #13
vilniusjug
 

Recently uploaded (20)

IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 

Java 8

  • 1. Java 8 Interesting parts Vaidas Pilkauskas, Kasparas Rudokas Vilnius JUG
  • 2. Agenda ● Lambda ● Date & Time ● PermGen ● Annotations
  • 4. lambda vs. closure A lambda is just an anonymous function. myCollection.filter(e ‑> e.length() >= 5) A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. int minLength = 5; myCollection.filter(new Predicate(){ boolean apply(MyElement e) { return e != null ? e.length >= minLength : false; } })
  • 5. Project Lambda (JSR 335) ● Language changes ○ Lambda Expression ○ Virtual Extension Method ● Library changes ○ Functional API ○ Parallel collections ○ Bulk Operations
  • 6. Problem String[] names = {"Alice", "Bob", "Charlie", Dave"}; Arrays.sort(names, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } });
  • 7. "tiny" anonymous inner class String[] names = {"Alice", "Bob", "Charlie", Dave"}; Arrays.sort(names, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } });
  • 8. "tiny" and useful ● callbacks ● runnables ● event handlers ● comparators ● ...and many other cases
  • 9. All we need! String[] names = {"Alice", "Bob", "Charlie", Dave"}; Arrays.sort(names, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } });
  • 10. Solution - closure String[] names = {"Alice", "Bob", "Charlie", Dave"}; Arrays.sort(names, (o1, o2) -> o1.compareToIgnoreCase(o2));
  • 11. What do we mean by closures? ● a unit of deferred execution ● code that can be passed as a value ● can be used in an assignment statement ● capture of a surrounding environment
  • 12. Lambda Expressions s -> s.length() (int x, int y) -> x+y () -> 42 (x, y, z) -> { if (x == y) return x; else { int result = y; for (int i = 1; i < z; i++) result *= i; return result; } }
  • 13. Lambda Syntax principally because something similar has been generally well-received in other Java-like languages (C# and Scala), and a clearly "better" alternative did not present itself
  • 15. Lambda ● Effectively final variables ● Shadowing
  • 16. Lambda ● Effectively final variables ● Shadowing ● break, continue must be local
  • 17. Lambda ● Effectively final variables ● Shadowing ● break, continue must be local ● this - lambda is not an instance method. (this == surrounding context object)
  • 18. Lambda ● Effectively final variables ● Shadowing ● break, continue must be local ● this - lambda is not an instance method. (this == surrounding context object) ● throw completes method abruptly
  • 19. Functional Interfaces A functional interface is an interface that has just one abstract method, and thus represents a single function contract.
  • 20. Functional Interfaces SAM - Single Abstract Method interfaces one method excluding Object methods interface Runnable { void run(); } // Functional interface Foo { boolean equals(Object obj); } // Not functional; equals is already an implicit member interface Comparator<T> { boolean equals(Object obj); int compare(T o1, T o2); } // Functional; Comparator has one abstract non-Object method
  • 21. Method References Method reference is a shorthand for a lambda invoking just that method System::getProperty "abc"::length String::length super::toString ArrayList::new Arrays.sort(ints, Integer::compareTo);
  • 22. Method References Static methods simply translate like lambda with same arguments and return type class Math { public static int max(int a, int b) {...} } interface Operator<T> { T eval(T left, T right); } Operator<Integer> lambda = (a, b) -> Math.max(a, b); Operator<Integer> methodRef = Math::max;
  • 23. Method References Non static method reference of type T translates like lambda with an additional argument of type T Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase (s2); //translates to: Comparator<String> c = String::compareToIgnoreCase;
  • 24. Method References Instance method reference translates like lambda with same arguments and return type (and implicit receiver) Callable<Integer> l = () -> "boo".length(); //translates to: Callable<Integer> c = "boo"::length;
  • 25. Method References String[] names = {"Alice", "Bob", "Charlie", Dave"}; Arrays.sort(names, (o1, o2) -> o1.compareToIgnoreCase(o2)); //translates to String[] names = {"Alice", "Bob", "Charlie", Dave"}; Arrays.sort(names, String::compareToIgnoreCase);
  • 26. Compatibility Cannot add new interface methods (without forcing current interface users to implement them) But we need new lambda enabled methods (on Java core libraries!)
  • 27. Default methods (also known as) ● virtual extension methods ● defender methods
  • 28. Default methods interface NormalInterface { void myNormalMethod(); void myDefaultMethod () default { System.out.println("-> myDefaultMethod"); } } class NormalInterfaceImpl implements NormalInterface { @Override public void myNormalMethod() { System.out.println("-> myNormalMethod"); } }
  • 29. Functional Collections Major changes in collection API: ● Internal iteration support with Iterable/Stream interfaces (forEach, filter, map, etc)
  • 30. Functional Collections Major changes in collection API: ● Internal iteration support with Iterable/Stream interfaces (forEach, filter, map, etc) ● Explicit parallel APIs for greater parallelism support. These can be combined with Fork/Join to divide the tasks
  • 31. Functional Collections Major changes in collection API: ● Internal iteration support with Iterable/Stream interfaces (forEach, filter, map, etc) ● Explicit parallel APIs for greater parallelism support. These can be combined with Fork/Join to divide the tasks ● Greater stress on immutability and avoiding in-place mutation which was done in the conventional for-each loops
  • 32. Example String[] names = {"Alice", "Bob", "Charlie", "Dave"}; List<String> filteredNames = Streams.stream(names) .filter(e -> e.length() >= 4) .into(new ArrayList<>()); filteredNames.stream().forEach(System.out::println);
  • 33. Streams ● No storage - nothing is stored in stream
  • 34. Streams ● No storage - nothing is stored in stream ● Functional in nature - new values are produced
  • 35. Streams ● No storage - nothing is stored in stream ● Functional in nature - new values are produced ● Laziness-seeking. Many operations can be implemented lazily
  • 36. Streams ● No storage - nothing is stored in stream ● Functional in nature - new values are produced ● Laziness-seeking. Many operations can be implemented lazily ● Bounds optional. Think of infinite stream
  • 37. Functional interfaces java.util.functions ● Predicate - a property of the object passed as argument ● Block - an action to be performed with the object passed as argument ● Mapper - transform a T to a U ● ...
  • 38. Parallelism //sequential int sum = myCollection.stream() .filter(b -> b.getColor() == BLUE) .map(b -> b.getWeight()) .sum(); //parallel int sum = myCollection.parallel() .filter(b -> b.getColor() == BLUE) .map(b -> b.getWeight()) .sum();
  • 39. Advantages ● Elements may be computed lazily. If we apply a Mapper to a collection of a thousand elements but only iterate over the first three, the remaining elements will never be mapped.
  • 40. Advantages ● Elements may be computed lazily. If we apply a Mapper to a collection of a thousand elements but only iterate over the first three, the remaining elements will never be mapped. ● Method chaining is encouraged. Hence there's no need to store intermediate results in their own collections.
  • 41. Advantages ● Elements may be computed lazily. If we apply a Mapper to a collection of a thousand elements but only iterate over the first three, the remaining elements will never be mapped. ● Method chaining is encouraged. Hence there's no need to store intermediate results in their own collections. ● Internal iteration hides implementation decisions. For example, we could parallelize a map() operation just by writing myCollection.parallel().map(e ‑> e.length()).
  • 42. Try it out today! The prototype compiler is being implemented in OpenJDK. ● Source code is available at http://hg.openjdk.java. net/lambda/lambda ● Binary snapshots of the lambda-enabled JDK prototype are available athttp://jdk8.java.net/lambda IDE support: ● Netbeans 8 Nightly Builds with experimental Lambda support ● IDEA 12 EAP with experimental Lambda support
  • 43. Date & Time API JSR 310
  • 45. Oldies: Date ● Mutable ● Years being indexed from 1900
  • 46. Oldies: Date ● Mutable ● Years being indexed from 1900 ● Months being indexed from 0
  • 47. Oldies: Date ● Mutable ● Years being indexed from 1900 ● Months being indexed from 0 Ex.: Date d = new Date(1L); System.out.println(d.toString());
  • 48. Oldies: Date ● Mutable ● Years being indexed from 1900 ● Months being indexed from 0 Ex.: Date d = new Date(1L); System.out.println(d.toString()); //Thu Jan 01 02:00:00 EET 1970
  • 50. Oldies: Calendar ● Mutable ● Not very convenient (lack of simple field methods)
  • 51. Oldies: Calendar ● Mutable ● Not very convenient (lack of simple field methods) ● Very difficult to extend (add new calendars)
  • 52. Oldies: Calendar ● Mutable ● Not very convenient (lack of simple field methods) ● Very difficult to extend (add new calendars) Ex.: Calendar c = Calendar.getInstance(); int weekday = c.get(DAY_OF_WEEK);
  • 53. Oldies: Calendar ● Mutable ● Not very convenient (lack of simple field methods) ● Very difficult to extend (add new calendars) Ex.: Calendar c = Calendar.getInstance(); int weekday = c.get(DAY_OF_WEEK); Date d = c.getTime();
  • 56. JSR 310 ● Immutable ● Defines consistent language for domain ○ Offset from UTC vs TimeZone ○ Machine vs Human ○ ISO 8601
  • 57. JSR 310 ● Immutable ● Defines consistent language for domain ○ Offset from UTC vs TimeZone ○ Machine vs Human ○ ISO 8601 ● No old Date/Calendar usage (clean)
  • 58. JSR 310 ● Immutable ● Defines consistent language for domain ○ Offset from UTC vs TimeZone ○ Machine vs Human ○ ISO 8601 ● No old Date/Calendar usage (clean) ● Extensible
  • 59. JSR 310 ● Immutable ● Defines consistent language for domain ○ Offset from UTC vs TimeZone ○ Machine vs Human ○ ISO 8601 ● No old Date/Calendar usage (clean) ● Extensible ● Led by JodaTime creator (S. Colebourne)
  • 60. Example: JSR 310 Clock clock = Clock.systemUTC(); LocalDate localDate = LocalDate.now(clock); //2012-11-13
  • 61. Example: JSR 310 Clock clock = Clock.systemUTC(); LocalDate localDate = LocalDate.now(clock); //2012-11-13 MonthDay brasilBday = MonthDay.of(JUNE, 21);
  • 62. Example: JSR 310 Clock clock = Clock.systemUTC(); LocalDate localDate = LocalDate.now(clock); //2012-11-13 MonthDay brasilBday = MonthDay.of(JUNE, 21); ZoneId zoneId = ZoneId.of("America/New_York"); Clock clock = Clock.system(zoneId); ZonedDateTime zonedDateTimeUS = ZonedDateTime.now(clock); //2012-11-11T04:17:58.693-05:00[America/New_York]
  • 63. Example: JSR 310 import static javax.time.calendrical.LocalPeriodUnit. HOURS; Period p = Period.of(5, HOURS); LocalTime time = LocalTime.now(); LocalTime newTime; newTime = time.plus(5, HOURS); // or newTime = time.plusHours(5); // or newTime = time.plus(p);
  • 64. Why not Joda Time? ● Machine timelines ● Pluggable chronology ● Nulls ● Internal implementation
  • 65. VM/GC JEP 122 & JEP 156
  • 66. PermGen removal ● Java Heap vs PermGen
  • 67. PermGen removal ● Java Heap vs PermGen
  • 68. PermGen removal ● Java Heap vs PermGen ● Why it was required anyway?
  • 69. PermGen removal ● Java Heap vs PermGen ● Why it was required anyway? ● So what?
  • 71. Type Annotations ● In Java 7 we have annotations on declarations Ex.: class SomeClass { … } class ListElement<E> { … } public void v() (int I) { long l; {
  • 72. Type Annotations ● JSR-308 brings annotations on Type use ● Are an enabler for the checkers framework Ex.: new @Interned MyObject(); myString = (@NonNull String) myObject; void monitorTemperature() throws @Critical TemperatureException { ... }
  • 73. Repeating Annotations ● Before @Schedules ({ @Schedule(dayOfMonth="Last"), @Schedule(dayOfWeek="Fri", hour="23") ({ public void doPeriodicCleanup() { ... }
  • 74. Repeating Annotations ● Before @Schedules ({ @Schedule(dayOfMonth="Last"), @Schedule(dayOfWeek="Fri", hour="23") ({ public void doPeriodicCleanup() { ... } ● After @Schedule(dayOfMonth="Last”) @Schedule(dayOfWeek="Fri", hour="23") public void doPeriodicCleanup() { ... }
  • 75. Q&A
  • 76. References * Lambda http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda http://openjdk.java.net/projects/lambda/ http://jcp.org/aboutJava/communityprocess/edr/jsr335/index2.html http://vimeo.com/48577033 (slides: http://www.slideshare.net/tkowalcz/java-gets-a-closure) http://datumedge.blogspot.co.uk/2012/06/java-8-lambdas.html http://www.theserverside.com/news/thread.tss?thread_id=68718 http://medianetwork.oracle.com/video/player/1785479333001 https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=6080 https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=5089 http://www.lektorium.tv/lecture/?id=14048 http://www.lektorium.tv/lecture/?id=14049 http://blog.xebia.com/2012/11/05/report-will-java-8s-lambda-change-the-face-of-the-world/ http://www.slideshare.net/fsarradin/java-8-lambda http://programmers.stackexchange.com/questions/173441/what-triggered-the-popularity-of-lambda-functions-in-modern-mainstream-programmi?newsletter=1&nlcode=29983% 7c903a http://www.slideshare.net/bje/java-closures * Collections http://www.javabeat.net/2012/05/enhanced-collections-api-in-java-8-supports-lambda-expressions/ http://cr.openjdk.java.net/~briangoetz/lambda/collections-overview.html http://architects.dzone.com/articles/java-collections-api
  • 77. References * Remove the Permanent Generation http://www.cubrid.org/blog/dev-platform/understanding-jvm-internals/ http://javaeesupportpatterns.blogspot.com/2011/10/java-7-features-permgen-removal.html http://java.dzone.com/articles/busting-permgen-myths https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=5135 * JSR 310: Date and Time API http://java.dzone.com/articles/introducing-new-date-and-time http://sourceforge.net/apps/mediawiki/threeten/index.php?title=ThreeTen http://www.infoq.com/news/2010/03/jsr-310 https://docs.google.com/document/pub?id=1rd8yplQZIRz3LxMzpVLuskr1b0HwBmK9PXpdgBYojSw http://sourceforge.net/apps/mediawiki/threeten/index.php?title=User_Guide https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=4350 * General Java8 http://openjdk.java.net/projects/jdk8/features http://www.pcadvisor.co.uk/news/software/3401314/oracle-java-upgrades-still-worthwhile-despite-postponed-features/ http://dhruba.name/2011/07/06/oracle-discusses-java-7-8-new-features-on-video/ http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2012/Java-8 http://www.parleys.com/#st=5&id=2850&sl=1 http://www.parleys.com/#st=5&id=2847 https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=2872 https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=10458