5 Features In Java 8 That WILL Change How You Code

By Tal Weiss —  March 18, 2014 — 8 Comments

Duke_8 copy

Java 8 is packed full of some really exciting features at both the JVM and language level. While some of the features initially envisioned for this release got scoped out or pushed out to release 9, there are literally dozens of new features. Many of the new additions are under-the-hood improvements either at the compiler, JVM or help-system level. As such, while we may benefit from them, there’s nothing we need to actively do (other than install Java 8 of course) to enjoy them.

Having said that, let’s look at 5 features that we feel are an absolute must for you to know about:

1. Lambda expressions

Even if we really didn’t want to go mainstream here, there’s little doubt that from a developer’s perspective, the most dominant feature of Java 8 is the new support for Lambda expressions. This addition to the language brings Java to the forefront of functional programming, right there with other functional JVM-based languages such as Scala and Clojure.

We’ve previously looked into how Java implemented Lambda expressions, and how it compared to the approach taken by Scala. From Java’s perspective this is by far one of the biggest additions to the language in the past decade.

At minimum, it’s recommended you become familiar with the Lambda syntax, especially as it relates to array and collection operations, where Lambdas have been tightly integrated into the core language libraries. It is highly likely that you’ll start seeing more and more code like the snippet below in both 3rd party and within your organization’s code.


Map<Person.Sex, List<Person>> byGender =
roster.stream().collect(Collectors.groupingBy(Person::getGender));

* A pretty efficient way of grouping a collection by the value of a specific class field.

2. Parallel operations

With the addition of Lambda expressions to arrays operations, Java introduced a key concept into the language of internal iteration. Essentially as developers we’re used to use loop operations as one of the most basic programming idioms, right up there with if and else.

The introduction of Lambda expressions turned that paradigm around, with the actual iteration over a collection on which a Lambda function is applied now carried out by the core library itself (i.e. internal iteration).

You can think of this as an extension of iterators where the actual operation of extracting the next item from a collection on which to operate is carried out by an iterator. An exciting possibility opened by this design pattern is to enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework. When dealing with server code that’s processing lengthy collections on a continuous basis, this can lead to major throughput improvements with relatively little work from your end.

Here’s the same snippet as above, but using the framework’s new parallel processing capabilities -


ConcurrentMap<Person.Sex, List<Person>> byGender =
roster.parallelStream().collect(
Collectors.groupingByConcurrent(Person::getGender));

* It’s a fairly small change that’s required to make this algorithm run on multiple threads.

3. Java + JavaScript = ❤

Java 8 is looking to right one of its biggest historical wrongs – the ever growing distance between Java and JavaScript, one that has only increased in the past few years. With this new release, Java 8 is introducing a completely new JVM JavaScript engine – Nashorn. This engine makes unique use of some of the new features introduced in Java 7 such as invokeDynamic to provide JVM-level speed to JavaScript execution right there with the likes of V8 and SpiderMonkey.

This means that the next time you’re looking to integrate JS into your backend, instead of setting up a node.js instance, you can simply use the JVM to execute the code. The added bonus here is the ability to have seamless interoperability between your Java and JavaScript code in-process, without having to use various IPC/RPC methods to bridge the gap.

4. New date / time APIs

The complexity of the current native Java library API has been a cause of pain for Java developers for many years. Joda time has been filling this vacuum for years now, and with Java 8. An immediate question that arose early on was why didn’t Java 8 adopt Joda as its native time framework. Due to what was perceived as a design flaw in Joda, Java 8 implemented its own new date / time API from scratch. The good news is that unlike Calendar.getInstance(), the new APIs were designed with simplicity in mind, and clear operations to operate on manipulated values in both human readable and machine time formats.

5. Concurrent accumulators

One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads. There have been many idioms to do this over the years, starting from synchronized blocks (which introduce a high level of contention), to read/write locks to AtomicInteger(s). While the last ones are more efficient, as they rely directly on processor CAS instructions, they require a higher degree of familiarity to implement the required semantics correctly.

With Java 8 this problem is solved at the framework level with new concurrent accumulator classes that enable you to very efficiently increase / decrease the value of a counter in a thread safe manner. This is really a case where it’s not a question of taste, or preference – using these new classes in your code is really a no-brainer.

Are there any other language features you think every developers should know about? Add them in the comments section.

lambda

Compiling Lambda Expressions: Scala vs. Java 8 – read more

Duke_8 copy

5 Features In Java 8 That WILL Change How You Code - read more


fredForBlog

Takipi detects all your exceptions and errors and tells you why they happen. Even across multiple threads and machines. Installs in 1min. Less than 2% overhead - Try it free

 

duke

Already using Java 8? Try Takipi for Java 8

Tal Weiss

Posts Twitter

Tal is the CEO of Takipi. Tal has been designing scalable, real-time Java and C++ applications for the past 15 years. He still enjoys analyzing a good bug though, and instrumenting code. In his free time Tal plays Jazz drums.
  • Yeroc

    I’m curious regarding the supposed performance of the Nashorn Javascript engine. It has been advertised as being very fast from the original announcements but the only benchmarking I’ve seen (https://github.com/tadas-subonis/java-nashorn-performance-sandbox) shows it being slower than the venerable Rhino Javascript engine and a long ways behind V8 and raw Java. Have you seen any evidence to suggest the Nashorn engine is really as fast as promised?

    • http://www.takipi.com/ Tal Weiss

      Hey Yeroc,

      You’re right that performance data for Nashorn is still scarce. Preliminary data (e.g. http://wnameless.wordpress.com/2013/12/10/javascript-engine-benchmarks-nashorn-vs-v8-vs-spidermonkey/) does show that it’s not as fast a V8.

      My sense from researching it (and this is only me, so anyone thinking differently please chime in) is that due to its nature as a JVM compiled language, Nashorn will see slower startup times until the underlying JVM JIT compiles and optimizes.

      Since Nashorn is heavily dependent on dynamic linking (i.e. invokeDynamic) there is additional linking time. However once that’s done, it will reach speeds that far exceed Rhino, which wasn’t not designed to use these Java 7 introduced features.

      Overall, my sense is that you’ll get a major speed increase over Rhino, and eventually reach something like ~80% performance (putting any graphics parts aside) of a V8, which is JS’s flagship engine.

      The upside of course is that integration of JS with Java should now become almost second nature for server applications.

  • http://www.palcomonline.com/ Rakesh Khuntia

    Thanks for your insight! I have tried the Dedicated Server in Australia and having a Dedicated Hosting really is beneficial.

  • Olivier Jacquemart

    It seems like the javadoc has moved, the LongAccumulator link should be: http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/LongAccumulator.html

    Great article, BTW.

    • http://www.takipi.com/ Tal Weiss

      Thanks Olivier!

  • Giovanni Candido da Silva

    When you say “Java 8 is looking to right one of its biggest historical wrongs – the ever growing distance between Java and JavaScript”, it seen like you are suggesting that java and JavaScript are in some way related, but they aren’t, in fact JavaScript is related to java in the same level that PHP is. The name was a joke from his creator and confuse much people.

    • http://www.takipi.com/ Tal Weiss

      Hi Giovanni,

      Thanks for the comment. You’re right in that JS and Java are diff languages (i.e. “car and carpet”). What Nashorn is trying to achieve is interoperability between the two languages, having them run on a shared run time in the same way that Java and Scala can interop together very well while still being totally different languages.

  • Yakov

    Hi Tal,

    what about new interface methods – I believe they are added in Java 8. Static and default methods with concrete implementation are allowed in interfaces. These methods are also called defender methods. As Oracle site says: “Default methods enable new functionality to be added to the interfaces
    of libraries and ensure binary compatibility with code written for older
    versions of those interfaces.”

    I know I am late with this addition, but better late than never :-)