JVM Advent

The JVM Programming Advent Calendar

Java – far sight look at JDK 8

The world is changing slowly but surely. After the changes that gave java a fresher look with JDK 7, the java community is looking forward to the rest of the improvements that will come with JDK 8 and probably JDK 9. The targeted purpose of JDK 8 was to fill in the gaps in the implementation of JDK 7 – part of the remaining puzzle pieces laking from this implementation, that should be available for the broad audience by in late 2013 is to improve and boost the language in three particular directions:

  • productivity
  • performance
  • modularity

So from next year, java will run everywhere (mobile, cloud, desktop, server etc.), but in an improved manner. In what follows I will provide a short overview of what to expect from 2013 – just in time for New Year’s Resolutions – afterwards I will focus mainly on productivity side with emphasis on project lambda and how will its introduction affect the way we code.

Productivity

In regards of productivity JDK 8 targets two main areas: – collections – a more facile way to interact with collections through literal extensions brought to the language – annotations – enhanced support for annotations, allowing writting them in contexts where are currently illegal (e.g. primitives)

Performance

The addition of the Fork/Join framework to JDK 7, was the first step that java took in the direction of multicore CPUs. JDK 8 takes this road even further by bringing closures’ support to java (lambda expression, that is). Probably the most affected part of java will be the Collections part, the closures combined with the newly added interfaces and functionalities pushing the java containers to the next level. Besides the more readable and shorter code to be written, by providing to the collections a lambda expression that will be executed internally the platform can take advantage of multicore processors.

Modularity

One of the most interresting pieces for the community was project jigsaw: “The goal of this Project is to design and implement a standard module system for the Java SE Platform, and to apply that system to the Platform itself and to the JDK.”. I am using past tense because, for the those of us that were hoping to get rid of the classpaths and classloaders, we have to postpone our exciment for Java 9, as for that point of time was also project jigsaw postponed.
To have a clearer picture of how the remaning Java Roadmap 2013:

2013/01/31 M6 Feature Complete
2013/02/21 M7 Developer Preview
2013/07/05 M8 Final Release Candidate
2013/09/09 GA General Availability

Besides project jigsaw another big and exciting change that will come (in this version), is the support for closures. Provided through the help of lambda expressions they will improve key points of the JDK.

Lambdas

Getting started

First and first of all one should get a lambda enabled SDK. In this direction there are two ways to obtain one:

 * the one intended for the brave ones: build it from the sources 
 * the convenient one: downloading an already compiled version of the SDK 

 Initially I started with building it from the sources, but due to the lack of time and too many warnings related to environment variables, I opted for the lazy approach and took the already existing JDK. The other important tool is a text editor to write the code. As it happened until now, tipically first came the JDK release and after a period of time, an enabled IDE came out. This time it is different, maybe also due to the transparency and the broad availability of the SDK through openjdk. Some days ago, the first Java 8 enabled IDE was realesed by JetBrain. So IntelliJ IDEA version 12 is the first IDE to provide support for JDK 8, besides are improvements? So for testing purposes I used IntelliJ 12 Community Edition together with JDK 8 b68, on a Windows 7, x64 machine. For those of you that prefer Netbeans, a nightly build with lambda support is available for download.

Adjusting to the appropriate mindset.

Before starting to write improved and cleaner code using the newly provided features, one must get a grasp on a couple new concepts – I needed to, anyway.

  • What is a lambda expression? The easiest way to see a lambda expression is just like a method: “it provides a list of formal parameters and a body—an expression or block— expressed in terms of those parameters.The parameters of a lambda expression can be either declared or inferred, when the formal parameters have inferred types, then these types are derived from the functional interface type targeted by the lambda expression. From the point of view of the returned value, a lambda expression can be void compatible – they don’t return anything or value compatible – if any given execution path returns a value.
    Examples of lambda expressions:
    (a) (int a, int b) -> a + b

    (b) (int a, int b) -> {
    if (a > b) {
    return a;
    } else if (a == b) {
    return a * b;
    } else {
    return b;
    }
    }

  • What is a functional interface? A functional interface is an interface that contains just one abstract method, hence represents a single method contract. In some situations, the single method may have the form of multiple methods with override-equivalent signatures, in this case all the methods represent a single method. Besides the typical way of creating an interface instance by creating and instantiating a class, functional interface instances can be created also by usage of lambda expressions, method or constructor references.
    Example of functional interfaces:
    // custom built functional interface
    public interface FuncInterface {
    public void invoke(String s1, String s2);
    }

    Example of functional interfaces from the JAVA API:

      java.lang.Comparable
    java.lang.Runnable
    java.util.concurrent.Callable
    java.awt.event.ActionListener

    So let’s see how the starting of a thread might change in the future:
    OLD WAY:

       new Thread(new Runnable() {
    @Override
    public void run() {
    for (int i=0; i< 9; i++) {
    System.out.println(String.format("Message #%d from inside the thread!", i));
    }
    }
    }).start();

    NEW WAY:

       new Thread(() -> {
    for (int i=0; i< 9; i++) {
    System.out.println(String.format("Message #%d from inside the thread!", i));
    }
    }).start();

    Even if I didn’t write for some time any java Swing, AWT related functionality I have to admit that lambdas will give a breath of fresh air to the Swing developers Action listener addition:

      JButton button = new JButton("Click");

    // NEW WAY:
    button.addActionListener( (e) -> {
    System.out.println("The button was clicked!");
    });

    // OLD WAY:
    button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("The button was clicked using old fashion code!");
    }
    });

  • Who/What is SAM? SAM stands for Single Abstract Method, so to cut some corners we can say that SAM == functional interface. Even if in the initial specification, also abstract classes with only one abstract method were considered SAM types, some people found/guessed also the reason why. 
  • Method/Constructor referencing
  • The lambdas sound all nice and all? But somehow the need for functional interface is somehow to some extend restrictive – does this mean that I can use only interfaces that contain a single abstract method? Not really – JDK 8 provides an aliasing mechanism that allows “extraction” of methods from classes or objects. This can be done by using the newly added :: operator. It can be applied on classes – for extraction of static methods or on objects for extraction of methods. The same operator can be used for constructors also.
    Referencing:

    interface ConstructorReference {
    T constructor();
    }

    interface MethodReference {
    void anotherMethod(String input);
    }

    public class ConstructorClass {
    String value;

    public ConstructorClass() {
    value = "default";
    }

    public static void method(String input) {
    System.out.println(input);
    }

    public void nextMethod(String input) {
    // operations
    }

    public static void main(String... args) {
    // constructor reference
    ConstructorReference reference = ConstructorClass::new;
    ConstructorClass cc = reference.constructor();

    // static method reference
    MethodReference mr = cc::method;

    // object method reference
    MethodReference mr2 = cc::nextMethod;

    System.out.println(cc.value);
    }
    }

  • Default methods in interfaces
  • This means that from version 8, java interfaces can contain method bodies, so to put it simple java will support multiple inheritance without the headaches that usually come with it. Also, by providing default implementations for interface methods one can assure ensure that adding a new method will not create chaos in the implementing classes. JDK 8 added default methods to interfaces like java.util.Collection or java.util.Iterator and through this it provided a mechanism to better use lambdas where it is really needed.
    Notable interfaces added:

       java.util.stream.Streamable
    java.util.stream.Stream

    Improved collections’ interaction In my opinion all the changes that come with project lambda are great additions to the language, that will make it align with the current day standards and make it simpler and leaner but probably the change that will have the biggest productivity impact and the biggest cool + wow effect is definitely the revamping of the collections framework. No, there is no Collection 2 framework, we still have to cope with type erasure for now, but java will make another important shift: from external to internal iteration. By doing so, it provides the developer the mechanism to filter and aggregate collections in an elegant manner and besides this to push for more efficiency. By providing a lambda expression that will be executed internally, so multicore processors can be used to their full power. Let’s consider the following scenarios:
    a. Considering a list of strings, select all of them that are uppercased written. How would this be written? OLD WAY:

      
    //.....

    List inputList = new LinkedList<>();
    List upper = new LinkedList<>();

    // add elements

    for (String currentValue : inputList) {
    if (currentValue != null && currentValue.matches("[A-Z0-9]*")) {
    upper.add(currentValue);
    }
    }

    System.out.println(upper);

    //….. NEW WAY:

      
    //.....
    inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).into(upper);


    b. Consider that you would like to change all the extracted characters to lowercase. Using the JDK8 way this would look like this:

     
    // .....
    inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).map(String::toLowerCase).into(upper);


    c. And how about finding out the number of characters from the selected collection

     
    // .....

    int sumX = inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).map(String::length).reduce(0, Integer::sum);

    Used methods:

     default Stream stream() // java.util.Collection
    Stream filter(Predicate predicate) // java.util.stream.Stream
    IntStream map(IntFunction mapper) //java.util.stream.Stream


    d. What if I would like to take each element from a collection and print it?

     //OLD WAY:
    for (String current : list) {
    System.out.println(current);
    }

    //NEW WAY:
    list.forEach(x -> System.out.println(x));


    Besides the mentioned functionality, JDK 8 has are other interesting news also, but for brevity reasons I will stop here. More information about it can be found on the JDK 8 Project lambda site or the webpage of the JSR 337.
    To conclude, Java is moving forward and I personally like the direction it is heading, another point of interest would be to point of time when library developers start adopting JDK 8 too. That will be for sure interesting. Thank you for your time and patience, I wish you a merry Christmas.

    Resources

    Brian Goetz resource folder: http://cr.openjdk.java.net/~briangoetz/lambda
    Method/constructor references: http://doanduyhai.wordpress.com/2012/07/14/java-8-lambda-in-details-part-iii-method-and-constructor-referencing

Meta: this post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on! Want to write for the blog? We are looking for contributors to fill all 24 slot and would love to have your contribution! Contact Attila Balazstocontribute!
Disclaimer: This post was based on the JDK8 lambda enabled SDK from 15. December 2012, some features might be subject to change.

Author: olimpiu pop

Next Post

Previous Post

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 JVM Advent | Powered by steinhauer.software Logosteinhauer.software

Theme by Anders Norén