9 new features in Java 9

More than three years after the release of Java 8, the next version is now just around the corner with a tentative release date of September 21st, 2018. You may have heard about Java 9’s module system, but there’s even more to this new version. Here are nine exciting new features that will ship with Java 9.

1. The Java Platform module system

The defining feature for Java 9 is an all-new module system. When codebases grow larger, the odds of creating complicated, tangled “spaghetti code” increase exponentially. There are two fundamental problems: It is hard to truly encapsulate code, and there is no notion of explicit dependencies between different parts (JAR files) of a system. Every public class can be accessed by any other public class on the classpath, leading to inadvertent usage of classes that weren’t meant to be public API. Furthermore, the classpath itself is problematic: How do you know whether all the required JARs are there, or if there are duplicate entries? The module system addresses both issues.

Modular JAR files contain an additional module descriptor. In this module descriptor, dependencies on other modules are expressed through`requires` statements. Additionally, `exports` statements control which packages are accessible to other modules. All non-exported packages are encapsulated in the module by default. Here’s an example of a module descriptor, which lives in ``:

2. Linking

When you have modules with explicit dependencies, and a modularized JDK, new possibilities arise. Your application modules now state their dependencies on other application modules and on the modules it uses from the JDK. Why not use that information to create a minimal runtime environment, containing just those modules necessary to run your application? That’s made possible with the new jlink tool in Java 9. Instead of shipping your app with a fully loaded JDK installation, you can create a minimal runtime image optimized for your application.

3. JShell: the interactive Java REPL

Many languages already feature an interactive Read-Eval-Print-Loop, and Java now joins this club. You can launch jshell from the console and directly start typing and executing Java code. The immediate feedback of jshell makes it a great tool to explore APIs and try out language features.

4. Improved Javadoc

Sometimes it’s the little things that can make a big difference. Did you use Google all the time to find the right Javadoc pages, just like me? That’s no longer necessary. Javadoc now includes search right in the API documentation itself. As an added bonus, the Javadoc output is now HTML5 compliant. Also, you’ll notice that every Javadoc page includes information on which JDK module the class or interface comes from.

5. Collection factory methods

Often you want to create a collection (e.g., a List or Set) in your code and directly populate it with some elements. That leads to repetitive code where you instantiate the collection, followed by several `add` calls. With Java 9, several so-called collection factory methods have been added:

Set<Integer> ints = Set.of(1, 2, 3);
List<String> strings = List.of("first", "second");

Besides being shorter and nicer to read, these methods also relieve you from having to pick a specific collection implementation. In fact, the collection implementations returned from the factory methods are highly optimized for the number of elements you put in. That’s possible because they’re immutable: adding items to these collections after creation results in an `UnsupportedOperationException`.

6. Stream API improvements

The Streams API is arguably one of the best improvements to the Java standard library in a long time. It allows you to create declarative pipelines of transformations on collections. With Java 9, this only gets better. There are four new methods added to the Stream interface: dropWhile, takeWhile, ofNullable. The iterate method gets a new overload, allowing you to provide a Predicate on when to stop iterating:

IntStream.iterate(1, i -> i < 100, i -> i + 1).forEach(System.out::println);

The second argument is a lambda that returns true until the current element in the IntStream becomes 100. This simple example therefore prints the integers 1 until 99 on the console.

Besides these additions on Stream itself, the integration between Optional and Stream has been improved. It’s now possible to turn an Optional object into a (possibly empty) Stream with the new `stream` method on Optional:

Stream<Integer> s = Optional.of(1).stream();

Turning an Optional into a Stream is especially useful when composing complex Streampipelines.

7. Private interface methods

Java 8 brought us default methods on interfaces. An interface can now also contain behavior instead of only method signatures. But what happens if you have several default methods on an interface with code that does almost the same thing? Normally, you’d refactor those methods to call a private method containing the shared functionality. But default methods can’t be private. Creating another default method with the shared code is not a solution, because this helper method becomes part of the public API. With Java 9, you can add private helper methods to interfaces to solve this problem:

public interface MyInterface {

    void normalInterfaceMethod();

    default void interfaceMethodWithDefault() {  init(); }

    default void anotherDefaultMethod() { init(); }

    // This method is not part of the public API exposed by MyInterface
    private void init() { System.out.println("Initializing"); }

If you’re evolving APIs with default methods, private interface methods can be helpful in structuring their implementation.

8. HTTP/2

A new way of performing HTTP calls arrives with Java 9. This much overdue replacement for the old `HttpURLConnection` API also supports WebSockets and HTTP/2 out of the box. One caveat: The new HttpClient API is delivered as a so-called _incubator module_ in Java 9. This means the API isn’t guaranteed to be 100% final yet. Still, with the arrival of Java 9 you can already start using this API:

HttpClient client = HttpClient.newHttpClient();

HttpRequest req =

HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandler.asString());

Besides this simple request/response model, HttpClient provides new APIs to deal with HTTP/2 features such as streams and server push.

9. Multi-release JARs

The last feature we’re highlighting is especially good news for library maintainers. When a new version of Java comes out, it takes years for all users of your library to switch to this new version. That means the library has to be backward compatible with the oldest version of Java you want to support (e.g., Java 6 or 7 in many cases). That effectively means you won’t get to use the new features of Java 9 in your library for a long time. Fortunately, the multi-release JAR feature allows you to create alternate versions of classes that are only used  when running the library on a specific Java version:

│   └── versions
│       └── 9
│           └── multirelease
│               └── Helper.class
├── multirelease
    ├── Helper.class
    └── Main.class

In this case, multirelease.jar can be used on Java 9, where instead of the top-level multirelease.Helper class, the one under `META-INF/versions/9` is used. This Java 9-specific version of the class can use Java 9 features and libraries. At the same time, using this JAR on earlier Java versions still works, since the older Java versions only see the top-level Helper class.


Related posts

20 Replies to “9 new features in Java 9
  1. 無論您是首次置業、換樓或是物業投資者,富邦樓宇按揭服務,為您提供多元化按揭計劃,全面配合不同的財務需要;加上專業按揭顧問的一站式服務,助您抓緊每個 …

  2. 韓國膠原蛋白提拉線,在韓國又稱作FTL(Fine Thread Lifting細線埋入拉提術)」,可達到最新趨勢V臉回春效果。它是運用獲得韓國食品藥品管理局KFDA最高安全等級認證的可吸收縫線PDO (polydioxanone)的Fine Thread(細螺紋) 埋入皮膚真皮層裡作用,利用異物反應原理,促進皮膚真皮膠原的增生、刺激局部微循環、從而提拉皮膚和肌肉,增強皮膚彈性,達到提升、除皺,美白、嫩膚等多重回春效果。水光槍-美白祛斑-水潤亮肌

  3. 倩碧卓越润肤乳,全新的倩碧有油黄油.升级配方,创新修护科技,提升弹润膜力,带来内润外弹光采肌.全新倩碧天才黄油+,专注修护天然肌肤保护膜力,成就弹润膜力升级,内润外弹,卓效不凡,倩碧小黄油带来更好的滋润护肤体验!肉毒桿菌

  4. The Body Shop 美體小舖 【水嫩淨白系列】水嫩淨白雙效防曬粉餅SPF25PA+++的商品介紹 UrCosme (@cosme TAIWAN) 商品資訊 The Body Shop 美體小舖,水嫩淨白系列,水嫩淨白雙效防曬粉餅SPF25PA+++,有網友推薦最新1爽髮

  5. I and my pals have been following the excellent procedures from the blog and the sudden I got a horrible feeling I had not expressed respect to the blog owner for those techniques. My boys are already as a consequence very interested to read through them and have in actuality been enjoying these things. I appreciate you for genuinely simply accommodating as well as for having varieties of great resources millions of individuals are really eager to know about. My very own sincere regret for not expressing gratitude to earlier.

  6. I have to voice my appreciation for your kindness supporting people who really need help with your area of interest. Your personal commitment to passing the message along turned out to be especially practical and have in most cases allowed guys and women much like me to realize their dreams. Your interesting key points entails so much to me and extremely more to my office workers. Thank you; from everyone of us.

  7. Thanks a lot for providing individuals with such a marvellous opportunity to check tips from this web site. It is usually very brilliant and stuffed with amusement for me personally and my office mates to search the blog at a minimum thrice in one week to read through the newest things you have got. And of course, I’m just always amazed with the amazing inspiring ideas you give. Some 1 ideas in this post are certainly the simplest I have had.

  8. I want to convey my love for your generosity supporting those people that need help with in this theme. Your very own dedication to getting the message up and down was particularly good and have without exception allowed guys and women like me to attain their objectives. Your personal warm and friendly report means a lot a person like me and even more to my office workers. Regards; from everyone of us.

  9. I wish to express some thanks to you for bailing me out of such a trouble. Right after exploring throughout the the net and finding ideas that were not helpful, I figured my life was gone. Living without the approaches to the difficulties you’ve fixed by means of your entire report is a crucial case, and the ones which might have negatively damaged my career if I had not discovered the website. Your main training and kindness in touching the whole lot was very useful. I don’t know what I would have done if I had not come upon such a subject like this. I can also at this moment relish my future. Thanks so much for this expert and amazing guide. I won’t hesitate to recommend your blog post to anybody who requires direction on this matter.

  10. I precisely had to say thanks once again. I do not know what I might have undertaken without these ways shown by you directly on this problem. It has been the depressing problem for me, however , coming across the very well-written strategy you dealt with it forced me to weep with contentment. I am just thankful for this information and as well , expect you realize what a powerful job that you are doing teaching many others through your website. I am sure you’ve never come across all of us.

  11. I’m also commenting to let you be aware of of the nice discovery our princess undergone reading through your web page. She mastered numerous details, including what it is like to possess a marvelous giving mindset to make many more without problems master a number of complex issues. You undoubtedly exceeded people’s expectations. I appreciate you for showing those effective, healthy, educational and in addition easy thoughts on the topic to Julie.

  12. I wish to convey my affection for your generosity giving support to men and women that require guidance on in this question. Your personal commitment to getting the message across appears to be particularly powerful and has frequently encouraged employees like me to attain their dreams. Your new warm and friendly instruction means a lot a person like me and especially to my fellow workers. Thanks a lot; from each one of us.

  13. Thanks a lot for giving everyone an exceptionally marvellous opportunity to read in detail from here. It’s always very beneficial and full of a great time for me and my office colleagues to search your site at least thrice a week to read through the newest things you will have. Not to mention, I am also at all times satisfied with all the remarkable suggestions served by you. Selected two ideas on this page are rather the most efficient we have had.

  14. Needed to compose you this little bit of note to help thank you so much yet again over the wonderful pointers you’ve documented above. It is really pretty open-handed of you to grant without restraint what a number of people could have marketed as an ebook to make some cash for their own end, primarily considering that you could have done it if you ever decided. Those secrets as well acted to be the fantastic way to be certain that someone else have similar keenness much like my own to know the truth many more concerning this condition. I think there are many more enjoyable opportunities ahead for many who see your website.

  15. I simply wished to thank you very much once again. I am not sure what I could possibly have tried without those tactics provided by you directly on such area. It had become an absolute hard setting in my opinion, nevertheless seeing a new expert mode you solved the issue took me to jump with gladness. I am thankful for your information and have high hopes you know what an amazing job you are always accomplishing educating many people by way of a web site. I know that you’ve never come across all of us.

  16. I want to show some appreciation to this writer just for rescuing me from this particular dilemma. After browsing throughout the world wide web and coming across views which were not pleasant, I figured my entire life was over. Being alive minus the answers to the problems you have fixed through your entire site is a crucial case, as well as the kind that might have badly damaged my entire career if I had not come across your web blog. Your main expertise and kindness in maneuvering all things was crucial. I’m not sure what I would have done if I hadn’t encountered such a point like this. I’m able to at this point look ahead to my future. Thanks so much for the expert and result oriented help. I won’t think twice to propose your blog post to any individual who ought to have support on this topic.

  17. I simply wanted to compose a quick remark in order to thank you for these superb guidelines you are posting on this site. My extensive internet search has at the end been honored with sensible suggestions to exchange with my neighbours. I would mention that we website visitors actually are quite lucky to exist in a fine place with so many wonderful professionals with helpful tricks. I feel rather grateful to have used your entire webpages and look forward to tons of more amazing minutes reading here. Thanks again for a lot of things.

Leave a Reply