Friday, November 16, 2018

JDK 12's Files.mismatch Method

JDK 12 introduces a new method to the Files class. The method, Files.mismatch(Path,Path), has been introduced to JDK 12 via JDK-8202302 and is available in JDK 12 Early Access Build 20 (same early access build that supports the new {@systemProperty} Javadoc tag).

JDK-8202302 ["(fs) New Files.mismatch method for comparing files"] adds the Files.mismatch(Path,Path) method "to compare the contents of two files to determine whether there is a mismatch between them" and can be used to determine "whether two files are equal." There was talk at one time of adding a Files.isSameContent() method, but it was decided to use Files.mismatch(Path,Parh) because of its consistency "with the Arrays.mismatch and Buffer.mismatch methods."

The next code listing contains a simple Java class that demonstrates the new Files.mismatch(Path,Path) and contrasts it with Files.isSameFile(Path,Path).

package dustin.examples.jdk12.files;

import java.nio.file.Files;
import java.nio.file.Path;

import static java.lang.System.out;

/**
 * Demonstrate {@code Files.mismatch(Path,Path)} introduced with JDK 12
 * and useful for determining if two files have the same content even
 * if they're not the same files.
 */
public class FilesDemo
{
   public static void main(final String[] arguments) throws Exception
   {
      if (arguments.length < 2)
      {
         out.println("USAGE: FilesDemo <file1Name> <file2Name>");
         return;
      }

      final String file1Name = arguments[0];
      final Path file1Path = Path.of(file1Name);
      final String file2Name = arguments[1];
      final Path file2Path = Path.of(file2Name);

      out.println("\nFiles '" + file1Name + "' and '" + file2Name + "' are "
         + (Files.isSameFile(file1Path, file2Path) ? "the" : "NOT the")
         + " same.\n\n");
      out.println("\nFiles '" + file1Name + "' and '" + file2Name + "' are "
         + (Files.mismatch(file1Path, file2Path) == -1 ? "the" : "NOT the")
         + " same content.\n\n");
   }
}

When the above code is executed against various combinations of files, it provides results captured in the next table.

Files Relationship Files.isSameFile(Path,Path) Files.mismatch(Path,Path)
Same File true true
Copied File false true
Different Files false false
Soft-linked true true
Hard-linked true true

The addition of Files.mismatch(Path,Path) is another step in accomplishing JDK-6852033 ["Inputs/Outputs methods to make common I/O tasks easy to do"] and makes it easier to determine when two files that are not the same file are still "equal" or have the same content.

Thursday, November 15, 2018

JDK 12 Javadoc Tag for System Properties

JDK 12 Early Access Build 20 (2018/11/15) is available and can be used to try out the new Javadoc tag {@systemProperty}. The new {@systemProperty} Javadoc tag is discussed in the core-libs-dev mailing list message "FYI: new javadoc tag to document system properties" and was introduced in response to JDK-5076751 ["System properties documentation needed in javadocs"].

The {@systemPropery} Javadoc tag displays its contents as normal text in its generated output and makes the contents available to the Javadoc search introduced with JDK 9. This tag is intended to be used for documenting an application's system properties.

The following simple class will be used to demonstrate the new JDK 12 Javadoc tag {@systemProperty}:

package dustin.examples.jdk12.properties;

import static java.lang.System.out;

/**
 * Class with sole purpose to illustrate JDK 12's
 * support for {@literal {@systemProperty}}.
 */
public class PropertiesDemo
{
   /**
    * {@systemProperty blog.title} can be specified to
    * provide a blog title.
    */
   private final static String PROPERTY_NAME = "blog.title";

   public static void main(final String[] arguments)
   {
      final String property = System.getProperty(PROPERTY_NAME);
      out.println("Property " + PROPERTY_NAME + ": " + property);
   }
}

The above code example applies {@systemProperty} to the private attribute PROPERTY_NAME. Because the field if private, the Javadoc tool must be executed with the -private flag to have documentation generated for this field.

The next screen snapshot demonstrates the documentation generated for the simple class using the javadoc command-line tool included in JDK 12 Early Access Build 12 (which did not have support for {@systemProperty}).

The red ovals in the previous screen snapshot show that the {@systemProperty} tag is not handled properly in earlier versions of the JDK. The contents of that tag are NOT displayed and the "search" functionality does not match on the system property name.

The next screen snapshot demonstrates the documentation generated for this same class using the command-line javadoc that comes with JDK 12 Early Access Build 20.

The green ovals in the previous screen snapshot show that {@systemProperty} is better supported in Early Access Build 20 of OpenJDK JDK 12. The contents of that tag are correctly displayed in the Javadoc itself and the search capability now matches on the system property name. It is also worth noting that the text within {@systemProperty} is presented in the HTML with appearance similar to which {@code} is presented.

The addition of {@systemProperty} potentially makes it easier for developers to find relevant descriptions of system properties for an application among Javadoc-generated documentation. The aforementioned post "FYI: new javadoc tag to document system properties" discusses other Javadoc enhancements that could possibly be made to take advantage of this tag. The potential enhancements include "a 'summary page' that lists all the system properties", adding "information regarding the 'scope' of the definition", and allowing "a short description to be included in the {@systemProperty} tag" that "could be included in the search index, the A-Z index, and the summary page."

The Jonathan Gibbons FYI mailing list message that introduces {@systemProperty} also spells out its recommended usage:

Where should the tag be used? The tag should be used in the text of the defining instance of the property. This is where the characteristics of the system property are described, which may include information like: "what is the property for", "how and when is it set", "can it be modified", and so on.

The addition of {@systemProperty} to the Javadoc tool with JDK 12 Early Access Build 20 is a minor thing, but will allow developers to make documentation of important system properties more readily accessible for fellow developers.

Wednesday, November 14, 2018

Amazon Corretto: Another No-Cost JDK

In the blog post "A Tale of Two Oracle JDKs," I compared and contrasted the two JDKs provided by Oracle: Oracle OpenJDK and Oracle JDK (Java SE). There are numerous other JDK offerings available, most of which are based on OpenJDK. One of these is Amazon Corretto, which is the subject of this post.

Today's "What's New with AWS" post "Introducing Amazon Corretto (Preview)" announces Amazon Corretto as "a no-cost, multiplatform, production-ready distribution of the Open Java Development Kit (OpenJDK)." Amazon Corretto's main page describes what it has to offer: "Corretto comes with long-term support that will include performance enhancements and security fixes." This is significant because it advertises that Amazon will provide performance enhancements and security fixes to its JDK offerings past the 6 months for which Oracle has committed to making performance enhancements and security fixes to each new OpenJDK version.

The first version of Amazon Corretto is currently a preview version and is called Amazon Corretto 8 (which, of course, associates it with OpenJDK 8). The "List of Patches for Amazon Corretto 8 Preview" lists "the patches applied to OpenJDK for the Amazon Corretto 8 Preview." These currently include patches related to OpenJDK issues (including backports from OpenJDK 11) such as JDK-8187123 ["(reflect) Class#getCanonicalName and Class#getSimpleName is a part of performance issue"] and JDK-8213198 ["Not triggering mixed GCs in G1 leaves string table cleanup deferred"].

The Amazon Corretto FAQs presents the question, "What is included in Corretto's long-term support?" The answers to this question communicate that Amazon plans to "provide security updates for Corretto 8 until at least June 2023" and to "support Corretto 11 with quarterly updates until at least August 2024." That same answer tells us that plans are to release Amazon Corretto 11 in the first half of 2019. Current updates for both Amazon Corretto 8 and for Amazon Corretto 11 are planned to be made quarterly until at least their advertised ending month of support (June 2023 for Corretto 8 and August 2024 for Corretto 11).

There has been a lot of miscommunication recently about the required cost of purchasing Java in the future. Amazon Corretto is another supporte JDK distribution that will be free of cost. The Amazon Corretto FAQs feature the question, "Is there any cost associated with using Corretto?" The answers associated with that question are:

Corretto is distributed by Amazon under an Open Source license at no cost to you. It is licensed under the terms of the GNU Public License version 2 with the Class Path Exception (GPLv2 with CPE). Amazon does not charge for its use or distribution.

I highly recommend the Amazon Corretto FAQs to anyone potentially interested in adopting Amazon Corretto. In addition to providing answers about likely questions related to long-term support, licenses, and costs, these FAQs also explain the types of patches Amazon intends to make to OpenJDK distributions, explain the degree of drop-in replaceability of other OpenJDK-based distributions by Amazon Corretto, list the operating systems supported for running Amazon Corretto, and explain how Amazon Corretto can be used with or without use of Amazon Web Services (AWS).

Conclusion

These has been continuing confusion surrounding whether Java is still free or not. Amazon Corretto is another example of an OpenJDK-based JDK binary available free of cost with long-term support advertised.

Additional Resources

Tuesday, October 30, 2018

Java's Future-Looking Projects: Panama, Loom, Amber, and Valhalla

The press release "Oracle Code One Java Keynote Outlines the Future of Java" describes the Java Keynote at Oracle Code "highlight[ing] future projects" Project Valhalla, Project Panama, Project Amber, and Project Loom. This post provides brief summaries of each of these projects and some recent work associated with each of these projects for those who may not be familiar with the mentioned projects.

Project Panama

Project Panama is about "Interconnecting JVM and native code." Its introduction states, "We are improving and enriching the connections between the Java TM virtual machine and well-defined but 'foreign' (non-Java) APIs, including many interfaces commonly used by C programmers."

Build 0 (2018/10/24) of the Project Panama Early-Access Builds was released recently. As with other OpenJDK-related early access builds, this build is "intended for expert users" and "is provided as a convenience so that they don't need to build from the source code." One of its most significant issues to be aware of is, "Windows support not available."

Project Loom

The Project Loom page describes Loom: "The goal of this Project is to explore and incubate Java VM features and APIs built on top of them for the implementation of lightweight user-mode threads (fibers), delimited continuations (of some form), and related features, such as explicit tail-call."

The Project Loom proposal (titled "Project Loom: Fibers and Continuations for the Java Virtual Machine") begins, "Project Loom's mission is to make it easier to write, debug, profile and maintain concurrent applications meeting today's requirements."

The message "Kick off meeting for Project Loom" on the OpenJDK loom-dev mailing list states that "Project Loom has been up and running here for number of months doing some early exploration and prototyping of both delimited continuations and fibers." That message talks about expanding that effort with kick-off meeting and provides links to the aforementioned Project Loom Proposal and to the YouTube-hosted presentation "Project Loom with Ron Pressler and Alan Bateman."

Project Amber

The Project Amber page describes its goal "to explore and incubate smaller, productivity-oriented Java language features that have been accepted as candidate JEPs under the OpenJDK JEP process." There are some exciting features being explored via this project including Pattern Matching (JEP 305), Switch Expressions (JEP 325), Raw String Literals (JEP 326), Concise Method Bodies (draft JEP), and faster String.format and Objects.hash methods [JDK-8205637 ("Optimized invocation of String::format and Objects::hash")].

The list of JEPs just mentioned are evidence of the significant work underway on Amber.

Project Valhalla

All of these projects propose exciting additions to Java, but the one I'm most excited about is Project Valhalla and its Value Objects/Types (JEP 169). The Project Valhalla page describes this project's goal "to provide a venue to explore and incubate advanced Java VM and Language feature candidates."

Project Valhalla has seen significant developments in recent weeks, especially since and as a result of the Valhalla Executive Group Meeting on 10 October 2018. In the OpenJDK valhalla-spec-experts mailing list message "Entering the next phase of Project Valhalla," Brian Goetz writes that this meeting was a "super-productive meeting with broad attendance" that helped Valhalla developers "to thrash out where we are, and where we're going next." Goetz also states that "this marks the beginning of the Phase III of the project" and outlines what constituted Phase 1 and Phase 2. This same packed message also summarizes the next steps for Valhalla:

Looking ahead, our next target is L2 -- which will capture the choices we've made so far, provide a useful test bed for doing library experiments, and set the stage for drilling into the remaining open questions between here and L10. L10 is our target for a first preview, which should support value types and erased generics over values.

Another recent interesting Goetz message on the valhalla-spec experts mailing list is "Values and erased generics," in which Goetz provides a "a summary of the story we came up with for erased generics over values" that "builds on the typing story outlined in John's 'Q-Types in L-World' writeup." The title of that referenced John Rose writeup is currently, "Q-Types in L-World 10: Valhalla Working Group, Burlington, September 2018." A revision of proposed JVM specification changes for LW2 was announced earlier this month as well.

The amount of work being done related to Project Valhalla is made clear in the number of messages on the mailing list about this project. These include those previously mentioned as well as others such as "var, static factory method and value type constructor"; "Value types, encapsulation, and uninitialized values"; and "Array covariance".

There is also a series of Goetz messages focusing on specific lessons learned from the first two phases:

The OpenJDK valhalla-dev mailing list message "Valhalla project repository status: Branched off 'LW1' in preparation for 'LW2'" announces the creation of the "lw1" branch.

Conclusion

It's not surprising that these four projects were mentioned at Oracle Code One's Java Keynote. They cover many of the features to look forward to in Java's future.

Sunday, October 28, 2018

IBM to Acquire Red Hat: A Java-Oriented First Look

Oracle Corporation completed the process of acquiring Sun Microsystems nearly nine years ago. That was big news then and similarly big news was announced today: IBM and Red Hat have agreed to IBM's acquisition of Red Hat. The main IBM page announces "IBM to acquire Red Hat." It then states, "This changes everything." It is likely that this announced acquisition is going to leave many Java developers wondering what kinds of changes are coming to the Java ecosystem.

Since Oracle's acquisition of Sun Microsystems, Oracle has eliminated multiple products that were formerly competitive products. For example Oracle still has its JDeveloper IDE, but has provided NetBeans (acquired from Sun) to Apache Software Foundation. Oracle has also dropped commercial support for Sun-acquired GlassFish while retaining its WebLogic Java EE application server.

I, of course, have no idea what will happen to the products and tools available to Java developers as currently provided by IBM and Red Hat. However, there are some obvious overlaps that come to mind from this $34 billion (USD) acquisition.

Item Red Hat IBM
JDK Builds/Binaries OpenJDK IBM SDK / AdoptOpenJDK
Java EE Application Server JBoss / Wildfly WebSphere / Liberty
OpenJDK Support/Contributions OpenJDK Life Cycle and Support Policy IBM Supporting the Java Community
Java Community Process (JCP)
Executive Committee (EC)
Mark Little (Scott Stark alternate) Steve Wallin (Tim Ellison alternate)
Integrated Development Environment (IDE) Eclipse-based Red Hat JBoss Developer Studio Eclipse-based IBM Rational Application Developer for WebSphere

Both IBM's version and Red Hat's version of the acquisition press release (which share much of the same wording) state, "With this acquisition, IBM will remain committed to Red Hat's open governance, open source contributions, participation in the open source community and development model, and fostering its widespread developer ecosystem." Perhaps even more encouraging, the press releases also state, "Upon closing of the acquisition, Red Hat will join IBM's Hybrid Cloud team as a distinct unit, preserving the independence and neutrality of Red Hat's open source development heritage and commitment, current product portfolio and go-to-market strategy, and unique development culture. ... IBM intends to maintain Red Hat's headquarters, facilities, brands and practices."

Both IBM and Red Hat are significant contributors to OpenJDK and to Java in general. Therefore, it should not be surprising if Java developers wonder how this acquisition will affect these two organizations' respective contributions.

At the very least, I image the question "Why choose JBoss Enterprise Middleware over IBM WebSphere?" likely won't remain on the JBoss page after this acquisition.

Wednesday, October 10, 2018

Book Review: Java by Comparison

I accepted the invitation to review Java by Comparison: Become a Java Craftsman in 70 Examples (2018, The Pragmatic Bookshelf) because the premise of this book interested me. The book Software Craftsmanship: The New Imperative had a significant effect on me when I was a much less experienced software developer and I looked forward to reviewing Java by Comparison because of its connection with the concept of software craftsmanship and its examples being provided in the Java programming language. I was provided with the electronic version of the book and I chose the PDF format for my review.

Java by Comparison is written by Simon Harrer, Jörg Lenhard, and Linus Dietz and has over 160 pages of substantive content (not counting prefaces, forewords, table of contents, etc.). Java by Comparison features nine chapters and the 70 cases covered span the first eight of those nine chapters.

Java by Comparison uses the same format for eight of its nine chapters. Each of these eight chapters are divided into several items each and at least two code samples are presented for each item. The first code sample for each item is typically functionally correct code, but the second code sample for each item illustrates how that particular item's principle can be applied to improve that code. There are three samples of these items ("extracts") available on the book's web site to see what I'm attempting to explain here.

Java by Comparison covers specific principles that fall into the areas of clean code, stylistic considerations, readability considerations, comments, naming, exception handling, unit testing, object-oriented design, and using Java's functional capabilities that were largely introduced to the language with JDK 8. Simple code examples are used in each item to contrast minimally sufficient code with improved code.

The ninth and final chapter is different from the first eight chapters. That chapter has fewer code samples and more descriptive text of general practices experienced Java developers tend to adopt in areas such as static code analysis, build automation, continuous integration, logging, and working with concurrency. This chapter is mostly higher-level and provides a taste of these topics for the newer Java developer.

I consider the following to be strengths of Java by Comparison:

  • Content
    • Java by Comparison collects information useful to newer Java developers in a single location.
    • As Java by Comparison covers various topics, it also introduces useful side notes of value to newer Java developers. Here are some examples of this:
      • There is a side note about "Multiple Returns vs. Single Return per Method" in the section on avoiding unnecessary comparisons.
      • There is a side note about "Never Use Floating-Point Arithmetic for Money" in the section on using appropriate tolerance values in unit testing.
    • Java by Comparison uses several different parts of the JDK API to illustrate its points.
    • Most of the lessons discussed in Java by Comparison are ones that I've had to learn the hard way and I found myself agreeing with most of the recommendations (and I've even blogged on some of them).
  • Format
    • The format comparing working code with superior code is effective in illustrating the principle discussed in each item.
    • The authors find a nice balance of small, simple code examples and just enough text to cover the point.
  • Finish
    • Java by Comparison is polished and has very few grammatical errors or typos. This seems to be an increasingly rare characteristic of technical books.
    • Code listings have color-coded syntax and shaded background in the PDF version of the book.
    • PDF version provides links between pages that reference each other.
    • Links to online resources work from PDF.
    • An accessible errata is available.
  • Tone
    • The text in Java by Comparison is easy to read, highly approachable, succinct, and well suited for those newer to Java.
    • Java by Comparison makes recommendations, but is not overly prescriptive and on several occasions highlights that sometimes "best" is context-sensitive and can only be determined after trying different approaches.
    • Although written by three different authors, the writing of Java by Comparison is consistent and uniform.
  • References
    • Java by Comparison provides frequent references to books and online resources for additional details regarding the concepts it covers.
    • Java by Comparison's "Bibliography" lists several of the most influential books and posts in Java and software development.

Intended Audience

I would have liked to have had access to Java by Comparison when I was still relatively new to Java. I remember reading the first edition of Effective Java and learning some from it, but Java by Comparison would have been more appropriate for my level of comfort with Java at that time.

The "Acknowledgements" section of Java by Comparison provides insight into the intended audience. The authors started building "a collection of common issues" that students in their "Advanced Java Programming" class encountered. The "Who Should Read This Book" section of the book addresses the audience more directly, "This book is for people who are learning to program in Java at a beginner or intermediate level. It's also a classroom resource for teachers who coach new developers in their journey to become programmers." The authors add, "You should read this book after you’ve learned the basic Java syntax - after you're able to write small programs with conditions and loops and you know the basics of object-oriented programming." The authors even provide a FizzBuzz-based assessment for potential readers to determine if they have the minimum recommended Java ability to make this book useful to them.

I agree with the authors' recommendations regarding who will benefit most from Java by Comparison. However, I would add that even more experienced Java developers might benefit greatly from reading Java by Comparison if they have not spent much time reading things such as Effective Java, Clean Code, Holub on Patterns, or other books or online media regarding writing Java more effectively.

My Recommendation

Many developers new to Java who have started feeling comfortable with its syntax and basic APIs often ask what is the next best book from them to read. Java by Comparison now gives me an easy answer to that question. I will recommend this book to developers new to Java as an appropriate book for them to read before moving onto Clean Code and Effective Java.

Java by Comparison is also recommended for more experienced Java developers who have concentrated mostly on getting the job done in the past and would like to do a better job at writing code that is more than sufficient and is easier for the next developer who has to work with it.

Java by Comparison applies a novel approach to presenting ideas for beginning and intermediate Java developers to learn techniques they can practice to become better Java developers and to write better code that will benefit others and themselves.

Additional References

There are three sample "excerpts" available to give a prospective reader an opportunity to determine if he or she likes the format and style of writing. There are listed below. I have also included links to others' reviews of Java by Comparison because we all have different tastes and experiences and it might be helpful for prospective readers of Java by Comparison to read what others have said about the book.

Thursday, October 4, 2018

JDK 12 News (4 October 2018)

There has been significant news related to JDK 12 in recent days.

JDK 12 Early Access Build 14

JDK 12 Early Access Build 14 (2018/10/4) was released today. The release notes indicate that the fix for JDK-8210692 ["The 'com.sun.awt.SecurityWarning' class can be dropped"] is a significant part of this build. The class com.sun.awt.SecurityWarning, deprecated for removal with JDK 11, has now been removed altogether. Other links of interest related to OpenJDK 12 Early Access Build 12 include "Changes in this build" and "Issues addressed in this build". This build also includes, of course, the preview features switch expressions (JEP 325) and raw string literals (JEP 326) that I have blogged on previously.

JEP 340 Targeted for JDK 12

Mark Reinhold announced in the post "JEP proposed to target JDK 12: 340: One AArch64 Port, Not Two" that JEP 340 ["One AArch64 Port, Not Two"] is now targeted for JDK 12.

JEP 341 Targeted for JDK 12

Reinhold also announced in "JEP proposed to target JDK 12: 341: Default CDS Archives" that JEP 341 ["Default CDS Archives"] is also targeted for JDK 12.

JDK 12 Proposed Schedule Approved

In a third consecutive message on the OpenJDK jdk-dev mailing list, Reinhold announced in the message "Proposed schedule for JDK 12" that the proposed schedule for JDK 12 has been approved. General Availability of JDK 12 is currently planned for 19 March 2019. As of this writing, there are now four JEPs targeted for JDK: JEP 325, JEP 326, JEP 340, and JEP 341.