Java 8 features

My quick summary on Java 8 (Spider) new features (differences vs Java 7), will categorize like this:

+ Useful & Pragmatic: which can change the way we write Java code/design in a better way (actual improvement to productivity).

+ Impactful: which may change the way to code/design in Java, but less used in reality due to: “niche”, “underrated”

+ Complicated: which is not necessary most of the time. It may be even intrusive (garbage detected, please call GC)! These may come from the over-engineering attempts to defer other JDK implementations (Apache Harmony, for instance), or to prove Java is a superior programming language (but backfire horribly).

+ Misc: miscellaneous changes which improves usability or some graphic (AWT, Swing, …), but typically small.

 

In each category I’ll try to make the features easy to remember, by listing them in certain order, or some notes about intention/history of the feature.

(Oracle does not want to expose their adoption from open source projects, FYI)

 

.

Useful & Pragmatic

Functional Interface

The most noteworthy feature of Java 8 is support for function-like, so that it has nice syntax for common operations (usually on collections, where other function languages can do ‘one-liner’ with ease). It has new package java.util.function.* , but the easy to remember is to start with functional interface: 1 abstract method interface (with annotation @FunctionalInterface).

Example: Runnable interface always have 1 method void run() , it is a functional interface now. And its concurrent sibling Callable is FI now as well.

Some other interfaces like Iterable and Executor has 1 abstract method, but not annotated with @FunctionalInterface, though.

Exceptions: abstract method which has same signature with toString(), equals(), hashCode() of Object class does not count as functional interface abstract method.

Default methods

This feature helps provide implementations for other classes without being intrusive or creating extra classes (base abstract class inheritance is no longer necessary). In other words, it’s pretty similar to mix-in feature in some other languages (Python: MixIn, Ruby: include mixin, Scala: Trait, C#: virtual extension methods, Groovy: metaClass mixin, Clojure: protocol mixin, …).

Previously mix-in behavior in Java can be achieved only via AOP weaving (actually by bytecode manipulation libraries such as CGLib, Javassist, or ASM/BCEL).

For example the interface Iterable besides its abstract method iterator() , now have the nice forEach() method with default implementation (using new Consumer FI as a filter for the collection). Which means we can filter the list, set, … many collections in Java easier instead of boilerplate code for loop.

Moreover, the default method can be easily overridden by implementation in derived classes. To avoid “multi inheritance” issue (diamond inheritance), we can specify the parent implementation by: ParentA.super.defaultMethod(); or ParentB.super.defaultMethod();

Lambda methods

The “unnamed” methods. They help a lot with the abstract method, especially the functional interfaces method. It reduces a lot of boilerplate code, no need to create an anonymous class just to implement an interface method (the way pre Java 8).

Runnable r = () -> { System.out.println("Running!"); }

It also supports nice syntax to not declare even parameter type (if easily inferred). Hence it’s the most expected feature of Java 8 release. And it helps a lot with collection filter as well (even better than forEach method of Iterable), as a result it is used in a lot of places, even in default method implementations of the JDK.

It provides implementation without class inheritance, so it’s kind of “mix-in” feature as well, but IMO the default methods are the actual “mix-in” in Java. Some other people consider both as “mix-in” . Let’s say that Java 8 have the “mix-in” capability.

Method Reference

This is quite similar to Lambda functions. However we usually use this for simple, default JDK methods, prefer static method over instance method or constructor.

 

New Date & Time API (Joda)

This is kind of merging the Joda time library to Java and deprecate the old DateTime API, including parser and formatter API.

LocalDate localDate = LocalDate.parse("19/05/2014", DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd::MMM::uuuu HH::mm::ss")));

 

public class DateUtils {

  public static LocalDate asLocalDate(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
  }

  public static LocalDateTime asLocalDateTime(Date date) {
    //return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
  }
 
  public static Date asDate(LocalDate localDate) { 
    return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
  } 

  public static Date asDate(LocalDateTime localDateTime) { 
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
  } 
}

 

New JavaScript engine (Nashorn)

Nashorn engine replaces Rhino engine (from Mozilla). Both engines was benefited from invokedynamic bytecode keyword in Java 7.

(And invokedynamic was inspired from JRuby implementation, not javascript)

As a result, the new tool jjs replaces jscript tool as well (in JAVA_HOME/bin), respectively Nashorn and Rhino internally.

From my investigation, Nashorn runs faster, and it supports more utility than Rhino. Such as: better import, Java type, __FILE__, __LINE__, __DIR__ , …

 

.

Impactful

 

 

.

Complicated

 

 

.

Misc

 

 

.

 

Well, there are quite many changes in Java 8 so it’s not easy to remember all. I will consolidate into a better article/slide when I have spare time.

 

./.

Advertisements

About DucQuoc.wordpress.com

A coder, husband and brother...
This entry was posted in Coding, Reading. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s