SlideShare une entreprise Scribd logo
1  sur  13
7, 8 & 9
 Moving the language forward
by Mario Fusco
Red Hat – Senior Software Engineer
mario.fusco@gmail.com
twitter: @mariofusco
New in Java 7 – Released in July 2011
• JSR 292: Support for dynamically-typed
  languages (InvokeDynamic)
• JSR 334: Small language enhancements
  (Project Coin)
• JSR 166y: Concurrency and collection updates
  (Fork/Join framework)
• JSR 203: More new I/O APIs for the Java
  platform (NIO.2)
Switch on Strings
switch(dayOfWeek) {
    case "Monday" :
        System.out.println("Start of week");
        break;
    ....
    case "Sunday" :
        System.out.println("Hurrey.. its weekend");
        break;
}
Improved Exception handling
public void printFileContent(String fileName)
                                 throws IOException {
    Configuration cfg = null;
    try {
        String fileText = getFile(fileName);
        //...code to print content
    } catch (FileNotFoundException |
                       FileLockInterruptionException e1) {
        System.err.println("error while opening file");
        throw e1;
    } catch (ParseException e2) {
        System.err.println("Error processing file");
    }
}
Try with resources
try ( FileOutputStream fos = new FileOutputStream(file);
      InputStream is = url.openStream() )
{
    byte[] buf = new byte[4096];
    int len;
    while ((len = is.read(buf)) > 0) {
        fos.write(buf, 0, len);
    }
}
Diamond Operator
Map<Person, List<Address>>



  Underscores in numeric literals

static final int ONE_MILLION = 1_000_000
Fork/Join Framework
public class FileSizeFinder extends RecursiveTask<Long> {
    private final File file;
    public FileSizeFinder(File theFile) { file = theFile; }

    @Override public Long compute() {
        long size = 0;
        if (file.isFile()) return file.length();
        File[] children = file.listFiles();
        if (children == null) return size;
        List<ForkJoinTask<Long>> tasks = new ArrayList<>();
        for (File child : children) {
           if (child.isFile()) size += child.length();
           else tasks.add(new FileSizeFinder(child));
        }
        for (ForkJoinTask<Long> task : invokeAll(tasks)) size += task.join();
        return size;
    }
}

long total = new ForkJoinPool().invoke(new FileSizeFinder(new File(rootName)));
Coming in Java 8 – Early (hopefully) 2013
• JSR 335: Project Lambda
• JSR TBD: Language support for collections
• JSR 308: Annotations on Java types
• JSR 310: Date and Time API (from JodaTime)
• JSR 294: Language and VM support for
  modular programming
• JSR TBD: Project Jigsaw (Modularization)
Project Lambda - Background
public interface Comparator<T> {              Functional
    int compare(T o1, T o2);
}                                             Interface
Collections.sort(strings, new Comparator<String>() {
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
});


•   Bulky syntax
•   Confusion surrounding the meaning of names and this
•   Inability to capture non-final local variables
•   Inability to abstract over control flow
Lambda Expressions
Collections.sort(strings, (s1, s2) -> s1.compareToIgnoreCase(s2));



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



                 Method reference
Collections.sort(strings, String::compareToIgnoreCase);
Lambda support for collections
double maxScore = 0;
for (Student s : students) {
    if (s.gradYear == 2011) {
        maxScore = Math.max(maxScore, s.score);
    }
}



double maxScore = students.parallel()
                    .filter(s -> s.gradYear == 2011)
                    .map(s -> s.score)
                    .reduce(0, Math::max);
Default methods
interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove();

    void skip(int i) default {
        for (; i > 0 && hasNext(); i--) next();
    }

    boolean filter default
        Iterables::filter
}
What to expect from Java 9

Contenu connexe

Tendances

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
Mario Fusco
 

Tendances (20)

Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 

Similaire à Java 7, 8 & 9 - Moving the language forward

Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 

Similaire à Java 7, 8 & 9 - Moving the language forward (20)

Jug java7
Jug java7Jug java7
Jug java7
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian Network
 
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 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
 
Java
JavaJava
Java
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
 
Power tools in Java
Power tools in JavaPower tools in Java
Power tools in Java
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDB
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Spark what's new what's coming
Spark what's new what's comingSpark what's new what's coming
Spark what's new what's coming
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 

Plus de Mario Fusco (11)

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Lazy java
Lazy javaLazy java
Lazy java
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Java 7, 8 & 9 - Moving the language forward

  • 1. 7, 8 & 9 Moving the language forward by Mario Fusco Red Hat – Senior Software Engineer mario.fusco@gmail.com twitter: @mariofusco
  • 2. New in Java 7 – Released in July 2011 • JSR 292: Support for dynamically-typed languages (InvokeDynamic) • JSR 334: Small language enhancements (Project Coin) • JSR 166y: Concurrency and collection updates (Fork/Join framework) • JSR 203: More new I/O APIs for the Java platform (NIO.2)
  • 3. Switch on Strings switch(dayOfWeek) { case "Monday" : System.out.println("Start of week"); break; .... case "Sunday" : System.out.println("Hurrey.. its weekend"); break; }
  • 4. Improved Exception handling public void printFileContent(String fileName) throws IOException { Configuration cfg = null; try { String fileText = getFile(fileName); //...code to print content } catch (FileNotFoundException | FileLockInterruptionException e1) { System.err.println("error while opening file"); throw e1; } catch (ParseException e2) { System.err.println("Error processing file"); } }
  • 5. Try with resources try ( FileOutputStream fos = new FileOutputStream(file); InputStream is = url.openStream() ) { byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) > 0) { fos.write(buf, 0, len); } }
  • 6. Diamond Operator Map<Person, List<Address>> Underscores in numeric literals static final int ONE_MILLION = 1_000_000
  • 7. Fork/Join Framework public class FileSizeFinder extends RecursiveTask<Long> { private final File file; public FileSizeFinder(File theFile) { file = theFile; } @Override public Long compute() { long size = 0; if (file.isFile()) return file.length(); File[] children = file.listFiles(); if (children == null) return size; List<ForkJoinTask<Long>> tasks = new ArrayList<>(); for (File child : children) { if (child.isFile()) size += child.length(); else tasks.add(new FileSizeFinder(child)); } for (ForkJoinTask<Long> task : invokeAll(tasks)) size += task.join(); return size; } } long total = new ForkJoinPool().invoke(new FileSizeFinder(new File(rootName)));
  • 8. Coming in Java 8 – Early (hopefully) 2013 • JSR 335: Project Lambda • JSR TBD: Language support for collections • JSR 308: Annotations on Java types • JSR 310: Date and Time API (from JodaTime) • JSR 294: Language and VM support for modular programming • JSR TBD: Project Jigsaw (Modularization)
  • 9. Project Lambda - Background public interface Comparator<T> { Functional int compare(T o1, T o2); } Interface Collections.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); • Bulky syntax • Confusion surrounding the meaning of names and this • Inability to capture non-final local variables • Inability to abstract over control flow
  • 10. Lambda Expressions Collections.sort(strings, (s1, s2) -> s1.compareToIgnoreCase(s2)); Target typing Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase(s2); Method reference Collections.sort(strings, String::compareToIgnoreCase);
  • 11. Lambda support for collections double maxScore = 0; for (Student s : students) { if (s.gradYear == 2011) { maxScore = Math.max(maxScore, s.score); } } double maxScore = students.parallel() .filter(s -> s.gradYear == 2011) .map(s -> s.score) .reduce(0, Math::max);
  • 12. Default methods interface Iterator<E> { boolean hasNext(); E next(); void remove(); void skip(int i) default { for (; i > 0 && hasNext(); i--) next(); } boolean filter default Iterables::filter }
  • 13. What to expect from Java 9