Originally published in the March/April 2014 issue of Java Magazine. Subscribe today.
by Timothy Beneke
From embedded to the cloud, get there with Java 8.
Java 8, which encompasses both Java SE 8 and Java ME 8, might be the most significant expansion of the Java platform yet.
Lambda expressions and the Stream API increase the expressive power of the platform and make it easier for developers to take advantage of modern, multicore processors. Compact Profiles in Java SE 8 allow developers to use just a subset of the platform, and are a significant step toward the convergence of Java SE and Java ME. Java ME 8 itself, meanwhile, has been updated to include more-recent Java Virtual Machine (JVM), language, and library features while retaining the focus on small embedded devices. Java 8 allows developers to apply the same skill set across a wide range of scenarios, from the smallest embedded Internet of Things (IoT) devices to enterprise servers in the cloud.
As Mark Reinhold, chief architect of the Java Platform Group at Oracle, put it, “Java 8 is the first truly revolutionary release we’ve done in a very long time.”
Here, we take a look at eight key pieces of Java 8.
Lambda expressions are at the heart of Java SE 8. “Lambda expressions, also known as closures, are anonymous methods that provide developers with a simple and compact means for representing behavior as data,” explains Brian Goetz, Oracle’s Java language architect and Specification Lead for JSR 335, Lambda Expressions for the Java Programming Language. “This enables the development of libraries that do a better job of abstracting over behavior, which in turn leads to more-expressive, less error-prone code.”
More on Lambdas
While Java has always provided reasonable tools such as classes, inheritance, and generics for abstracting over data, Java SE 8 provides new tools for abstracting over behavior. As Goetz explains, “If we want to model a workflow such as ‘do A before you start, do B for every file in this group, do C if you encounter an error, and do D when you’re done,’ we don’t have ideal tools for expressing the behaviors A through D, and this affects the sort of APIs we design. We have to break up the phases of the workflow, and the client code has to be directly involved in each phase, rather than saying ‘here’s what I want; go do it.’ This negatively affects reusability, readability, and performance.”
According to Goetz, the typical developer’s initial experience with lambda expressions is likely to be through the powerful new APIs for manipulating collections. Business logic typically is full of ad hoc query-like calculations over collections; the core libraries now make it easier to express the “what” of such a query without getting bogged down in details about the “how.”
The other major language feature of Java SE 8 is default methods, which enable interfaces to evolve over time. Default methods are necessary for Java SE 8 given that some core library classes, such as Collections, are more than 15 years old. Without default methods, some core library classes would be unable to support lambdas.
“More generally,” explains Goetz, “if you want libraries to stay relevant over long periods of time, they need to be flexible, so we needed to address this problem while maintaining our commitment to compatibility.”
When asked about the challenges Java developers face in working with lambdas, Goetz is optimistic. “The big challenge,” he says, “is accepting that this is not simply a matter of new syntax; there are some new concepts that developers will have to learn just to be able to read Java code, even if they do not plan to take advantage of these new features in the code they write. There are also big additions to the core libraries that developers will have to learn—but these costs should be more than offset by increases in productivity and expressiveness.”
Goetz makes no effort to hide his enthusiasm for lambdas: “I think this is the most significant upgrade of the Java programming model ever—and yet, it still feels like the Java we know and love,” he insists. “In a few years, developers will wonder how they ever lived without it. I certainly do!”
More on Nashorn
Compact Profiles, three well-defined API subsets of the Java 8 specification, offer a convergence of the Java ME Connected Device Configuration (CDC) with Java SE 8. With full Java 8 language and API support, developers now have a single specification that will support the Java ME CDC class of devices under the Java SE umbrella. For many years, embedded developers have wanted to allow subsetting of the Java SE platform in order to deploy smaller binaries in their embedded devices. Compact Profiles enable the creation of applications that do not require the entire platform to be deployed and run on small devices. Because Compact Profiles are much smaller than the full Java SE Java runtime environment (JRE), they enable applications to be deployed on platforms with limited storage. The smallest of these runtimes is 11 MB, which is more than four times smaller than the equivalent traditional JRE.
More on Compact Profiles
Java SE applications can now be designed to run on resource-constrained devices by targeting the specific APIs that are available in Compact Profiles. The Compact Profiles were primarily designed for embedded developers who wish to use Java for the creation of embedded solutions with limited static and dynamic storage. By keeping the amount of RAM and flash to a minimum, the bill of materials (BOM) cost for embedded devices is also kept to a minimum, resulting in increased profit for device distributors.
Bob Vandette, consulting engineer at Oracle, sums it up: “With the introduction of Compact Profiles, we now have a single Java SE standard with all of the productivity that Java is famous for that can truly scale from small embedded IoT devices to large enterprise server installations.”
Java SE 8 introduces a new
java.time API with a fluent and familiar style that is easy to read and write without the aid of IDEs. It provides excellent support for the international ISO 8601 time standard that global businesses use and also supports the frequently used Japanese, Minguo, Hijrah, and Thai Buddhist calendars. Each of the new core Java classes—for date, time, date and time combined, time zones, instants, duration, and clocks—has a specific purpose and has explicitly defined behavior without side effects. The types are immutable to simplify concurrency issues when used in multitasking environments. In addition, the extensibility of the API enables the addition of new calendars, units, fields of dates, and times. Developers can focus on completing a particular task without being concerned about unrelated functions.
More on Date and Time
Calendartypes that hold a mutable value and are not multithread safe. Using immutable values eliminates many problems for multithreaded programming.
“The current APIs for
Calendar combine many functions in each type, which often results in unexpected interactions that increase programming complexity,” explains Riggs. “The new APIs offer greater clarity of purpose, ease of use, and maintenance.”
“JavaFX 8 is integrated with Java SE 8 and works well with lambda expressions. It simplifies many kinds of code, such as event handlers, cell value factories, and cell value factories on
TableView,” explains Richard Bair, client Java architect at Oracle. “It brings some much-requested new UI controls and APIs such as
TreeTableView and APIs that enable modal dialogs.”
More on JavaFX 8
In addition, says Bair, JavaFX 8 offers a powerful rich text node for the scene graph, and the Java community is fast at work on several projects building rich text and code editors on top of this support. In addition, the default look of JavaFX applications has been refreshed with a new theme, called “Modena.” JavaFX 8 also offers increased support for third-party components, many of which can now work out of the box. All of the above will lead to enhanced productivity for JavaFX developers, he says.
Much progress has also been made on the performance front, largely due to the effort to bring JavaFX to embedded devices such as the Raspberry Pi and Freescale i.MX 6 boards. Increased 3-D support in JavaFX has opened new opportunities for developers, with AMD contributing COLLADA importer functionality to OpenJFX, which is a lively and thriving community, Bair adds.
“The new Scene Builder 2, the first Scene Builder actually built with Scene Builder, has an excellent CSS inspector, so developers can better understand why things are styled as they are,” explains Bair. It is also modular and can be embedded in any IDE. Scene Builder 2 works with FXML, an open and published format, so developers can hack the FXML file directly. “I encourage everybody to download JavaFX 8, try it out, and provide feedback to the team,” he adds.
The Java community has been vital in the creation of Java 8. It has provided ongoing feedback to Specification Leads, made requests for new Java functionality, uncovered bugs, contributed to code fixes, and much more.
Java user groups (JUGs), which are centers of Java community learning and participation, have been essential. As Java Champion and SouJava JUG Leader Bruno Souza explains, “Java 8 has set a new standard of community participation. There are Java user groups all over the world running programs and providing feedback for the JCP specifications and being active in OpenJDK.” The OpenJDK community is where developers collaborate on the open source reference implementation of the Java SE platform.
The Adopt-a-JSR program, created to encourage JUG members, individuals, and other organizations to get involved in JSRs, has resulted in increased grassroots and developer participation in not only Java 8 but other emerging standards as well. More than 26 JUGs have participated in the program.
The Java Community Process (JCP), with its enhanced openness and flexibility, has made it easier for both organizations and individuals to contribute to the Java platform. “The JCP now has a much more transparent process,” says Souza. “It’s a lot easier for someone to go to the JCP site and get involved. This increased transparency has made it easier for the community to participate.”
More on Java ME 8
“Java ME 8 is a major step in the convergence of Java ME and Java SE and the unification of the Java ecosystem, enabling Java developers to more easily deploy their existing skills across a range of embedded devices, drawing upon the richness and portability of the Java platform,” explains Terrence Barr, senior technologist and product manager at Oracle who focuses on the IoT and embedded technologies. “This results in a faster time to market, as well as cross-platform compatibility and embedded device scalability.”
With the advent of Java ME 8, developers can take their existing skills and begin writing applications for the rapidly developing realm of embedded devices—using the same familiar platform, language, programming model, and tools. With the embedded space and the fast-developing IoT in a state of flux, Java ME 8 offers a flexible and scalable development/deployment environment.
See “Java ME 8 and the Internet of Things” in this issue for details.
“Java SE 8 offers an improved, more mature G1 garbage collector. G1’s scalability is getting better, and more work is being done concurrently,” explains Jon Masamitsu, principal member of the technical staff at Oracle. “G1’s basic design is not changing, but incremental improvements toward more-dependable pause times have been made in many areas. More generally, in all the garbage collectors the command-line flags are now more consistent, with flag discrepancies corrected. This should make it easier for users to switch among the different garbage collectors and have the command-line flags have a common meaning where possible.”
In addition, Java SE 8 removes the need to tune the permanent generation. The Java HotSpot VM’s internal representation of Java classes has been re-engineered and moved out of the permanent generation (which has been removed entirely) and moved into native memory and/or the Java heap. Previously, tuning the size of the permanent generation was a tiresome, trial-and-error process. The maximum size of the permanent generation had to be set at startup, and there was no intuitive way to know how large it should be. Developers need no longer guess about a size for the permanent generation.
Finally, Java ME 8 has been updated with the JVM, the language, and the libraries to be aligned with Java SE 8.
Java Language Architect Brian Goetz shows how the Java core libraries have been enhanced to enable more-query-like calculations over collections.
“Consider something like ‘find artists with albums that have fewer than eight tracks.’ This is easy enough to write with a for loop, but the resulting code is full of accidental detail about ‘how,’ which obfuscates the ‘what,’” he says. In Java SE 8, it looks like this:
Set<artists> artists = albums.stream() .filter(album -> album.getTracks().size() < 8) .map(album -> album.getArtist()) .collect(toSet());</artists>
“Here, we’ve said ‘give us the elements of albums, select the ones with fewer than eight tracks, for each of those get the artist, and then collect them into a set.’ The code reads like the problem statement, which is good because code that is easy to read also is more likely to be correct,” says Goetz.
This shift from handwritten loops to aggregate operations using lambdas and streams inverts the control of the computation. “With the for loop, the client is in control at every step, asking the Iterator for the next element on each iteration,” Goetz says. “With lambdas and streams, the library is in control, but still allows the computation to be easily customized by the client.”
He goes on to explain, “In the albums calculation above, it might look like we’re doing three passes on the data, but in fact the three are fused into a single pass. This is possible only because the client was able to express everything it wanted in one go, parameterizing the steps with various bits of behavior, rather than being involved in every loop iteration.”
Download Java 8
All in all, Java 8 offers a new opportunity for enhanced innovation for Java developers who operate on anything from tiny devices to cloud-based systems. We can expect increases in developer productivity and application performance through the reduced boilerplate code and increased parallel programming that lambdas offer. Java 8 offers best-in-class diagnostics, with a complete tool chain to continuously collect low-level and detailed runtime information.
By bringing the advantages of Java SE to embedded development, developers can transfer their Java skills to fast-evolving new realms in the IoT, enabling Java to support any device of any size. It is an exciting time to be a Java developer, so take it for a spin, and tell us about the ride.
Timothy Beneke is a freelance writer and editor, best known for his books on gender.