share

ENGINEERING

7min read

Exploring Java 9 - Java Platform Module System

The following post is the second one from our mini Java-series. If you are interested in JShell, check out the first one here!

Modularity is a known concept in software engineering. Writing unique units encapsulating functionality and exposing it through various interfaces is something we try to achieve in many fields nowadays. This attitude has a number of advantages. Thanks to it we:

  • make our design cleaner and easier to maintain
  • choose what tools to use in a more conscious way
  • make our applications smaller because we avoid using unnecessary things
  • possibly make our applications more scalable and improve performance

Java creators certainly know that. That’s why there’s Jigsaw. It is a huge project that was started at Sun way back in August 2008. Delayed due to technical and non-technical reasons (e.g. integrating Sun into Oracle) it’s finally there to make Java modular. Encompassing 6 JEPs, it will be a part of Java 9 release which is planned to happen in about 90 days.

Breaking The Monolith

As we take a look at Java Platform and the JDK we are probably not satisfied about its structure. This comes as no surprise - over the years Java has been designed without mechanisms that enforced modular design. The spirit of always being backwards compatible didn’t help either. Every release just made it bigger and more tangled. No wonder that the primary goal of the Jigsaw project is to cut the Java Platform and the JDK into smaller and more organized modules. Those could be used to build software without the need to include all APIs that are there in Java.

This job is a tough one. After making the decision to defer Project Jigsaw from Java 8 to Java 9 in 2012, Mark Reinhold, the Chief Architect of the Java Platform Group at Oracle, explained why it was so hard:

  • There are two main reasons. The first is that the JDK code base is deeply interconnected at both the API and the implementation levels, having been built over many years primarily in the style of a monolithic software system. We’ve spent considerable effort eliminating or at least simplifying as many API and implementation dependencies as possible, so that both the Platform and its implementations can be presented as a coherent set of interdependent modules, but some particularly thorny cases remain.

  • We want to maintain as much compatibility with prior releases as possible, most especially for existing classpath-based applications but also, to the extent feasible, for applications composed of modules.

From Mark Reinhold’s Blog “Project Jigsaw: Late for the train: The Q&A”

Now it seems that they succeeded in doing the job. All Java 9 modules are located in your $JAVA_HOME/jmods directory:

$ ls -l $JAVA_HOME/jmods

Each module has its interface that is exposed to other modules. They require each other and communicate only through exported packages. Developers can compile, package, deploy and execute applications that consist only of the selected modules and nothing else. This is a huge change.

Getting modular

There will be means to make our own code modular too. Let’s explain the basics on a simple Java application made of two modules:

  1. com.timeteller.clock: a module which contains SpeakingClock - simple class for printing current time to the stdout.
  2. com.timeteller.main: a module utilizing the functionality offered by com.timeteller.clock module.

The code, building and running instructions are located here.

The overall project structure looks like this:

$ tree
.
├── com.timeteller.clock
│   ├── com
│   │   └── timeteller
│   │       └── clock
│   │           └── SpeakingClock.java
│   └── module-info.java
└── com.timeteller.main
    ├── com
    │   └── timeteller
    │       └── main
    │           └── Main.java
    └── module-info.java

8 directories, 5 files

Classes Main and SpeakingClock are almost irrelevant when it comes to talking about modules. Jigsaw does not make them any different from previous Java implementations. All we have to know is that the main() method in the Main class uses the SpeakingClock’s method from the other module:

public static void main (String[] args) {
    SpeakingClock clock = new SpeakingClock();
    clock.tellTheTime(); // displays the time to stdout.
}

The most important part is hidden in the module descriptor files (module-info.java). They contain all the module-related metadata. They’re .java files but a little different, like this:

module com.timeteller.clock {
    exports com.timeteller.clock;
}

or this:

module com.timeteller.main {
    requires com.timeteller.clock;
}

It is a trivial configuration but you can learn the following:

  • module descriptor files are placed in the root folder of the module (by convention)
  • every module has a unique name
  • module descriptors define what packages are exported from the module and what modules do they require

The last bullet is strictly about the encapsulation I mentioned earlier. If you do not export your packages, they will remain hidden in your module - unavailable to other modules. Analogically with requiring. If something is exported that doesn’t mean that you can use it everywhere. You have to explicitly require it (except for the java.base module - conveniently, every module automatically requires it). If you don’t do it, the application won’t even compile.

Let’s also notice that the public keyword changes its meaning in Java 9. Before modules, it meant that a public code is visible everywhere. Now it means that the code is not visible outside the module if the package is not exported. It’s a good thing - this gives the possibility for hiding internal APIs. This is also one of the goals of project Jigsaw described in JEP 260. It’s also a source of fear of many developers - some APIs, eg. from sun.misc package get hidden and this may introduce complications while migrating to Java 9.

Building the app

We can create JARs the following way:

$ mkdir -p jars

$ mkdir -p build/classes/com.timeteller.clock
$ javac -d build/classes/com.timeteller.clock/ com.timeteller.clock/module-info.java com.timeteller.clock/com/timeteller/clock/SpeakingClock.java
$ jar -c -f jars/clock.jar -C build/classes/com.timeteller.clock/ .

$ mkdir -p build/classes/com.timeteller.main
$ javac -d build/classes/com.timeteller.main/ --module-path=jars com.timeteller.main/module-info.java com.timeteller.main/com/timeteller/main/Main.java
$ jar -c -f jars/timeTeller.jar --main-class com.timeteller.main.Main -C build/classes/com.timeteller.main .

To let the compiler know about the modules we must place them on the module path. This concept is quite similar to classpath - but for modules. When we build the com.timeteller.main module we put a jar with com.timeteller.clock on its module path. Otherwise it doesn’t find the necessary code and results in a compilation error:

$ javac -d build/classes/com.timeteller.main/ com.timeteller.main/module-info.java com.timeteller.main/com/timeteller/main/Main.java
com.timeteller.main/module-info.java:2: error: module not found: com.timeteller.clock
  requires com.timeteller.clock;
                         ^
1 error

Notice that the JARs we created here are modular too. They are just like the regular JARs except that they include module-info.class file (compiled module descriptor). This way they can be put both on modulepath and classpath.

Tailor-made run-time images

Project Jigsaw will equip Java 9 in some other useful things. Among them is The Java Linker - a tool which can be used to take only needed modules and create a custom run-time image. Instead of using the whole Java run-time (the 51 MB rt.jar) we can create our own “tailor-made” one:

$ jlink --module-path $JAVA_HOME/jmods:mlib:jars --add-modules com.timeteller.main --output timeteller-runtime

and use it to run our application:

$ ./timeteller-runtime/bin/java --module-path jars/ -m com.timeteller.main
Sun Apr 09 18:31:16 CEST 2017

The run-time size decreases - now it’s 35MB. This optimization is especially useful on devices that run low on memory. We can go further and try to make it even smaller getting to 21MB:

$ jlink --module-path $JAVA_HOME/jmods:mlib:jars --add-modules com.timeteller.main --output timeteller-runtime-compressed --compress=2 --strip-debug

The --compress flag enables compression of resources on three different levels: from no-compression to ZIP level compression. --strip-debug flag allows removing debug information from the runtime which would not be needed in a production system.

Summary

Java Platform Module System with modularized JDK and the Java platform itself is a long awaited change that is finally going to be there in the upcoming release. In this post, we shortly described it and showed jlink tool as a “cherry on the top”.

If you’re concerned about any problems that may appear while migrating your software to Java 9, there is a guide straight from Oracle. They strongly encourage developers to try it as soon as possible due to possible incompatibilities.

We are looking forward to seeing how the Module System is going to adopt in the world of Java software.

share


ŁukaszSoftware Engineer

LEARN MORE

Contact us if you have any questions regarding the article or just want to chat about technology, our services, job offers and more!

POLIDEA NEWSLETTER

Sign in and expect sharp insights, recommendations, ebooks and fascinating project stories delivered to your inbox

The controller of the personal data that you are about to provide in the above form will be Polidea sp. z o.o. with its registered office in Warsaw at ul. Przeskok 2, 00-032 Warsaw, KRS number: 0000330954, tel.: [0048795536436], email: [hello@polidea.com] (“Polidea”). We will process your personal data based on our legitimate interest and/or your consent. Providing your personal data is not obligatory, but necessary for Polidea to respond to you in relation to your question and/or request. If you gave us consent to call you on the telephone, you may revoke the consent at any time by contacting Polidea via telephone or email. You can find detailed information about the processing of your personal data in relation to the above contact form, including your rights relating to the processing, HERE.

Data controller:

The controller of your personal data is Polidea sp. z o.o. with its registered office in Warsaw at ul. Przeskok 2, 00-032 Warsaw, KRS number: 0000330954, tel.: [0048795536436], email: [hello@polidea.com] (“Polidea”)

Purpose and legal bases for processing:

 

Used abbreviations:

GDPR – Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016
on the protection of natural persons with regard to the processing of personal data and on the free movement
of such data, and repealing Directive 95/46/EC (General Data Protection Regulation)

ARES – Polish Act on Rendering Electronic Services dated 18 July 2002

TL – Polish Telecommunications Law dated 16 July 2004

1)        sending to the given email address a newsletter including information on Polidea’s new projects, products, services, organised events and/or general insights from the mobile app business world |art. 6.1 a) GDPR, art. 10.2 ARES and art. 172.1 TL (upon your consent)

Personal data:name, email address

2)       statistical, analytical and reporting purposes |art. 6. 1 f) GDPR (based on legitimate interests pursued by Polidea, consisting in analysing the way our services are used and adjusting them to our clients’ needs, as well as developing new services)

Personal data:name, email address

Withdrawal of consent:

You may withdraw your consent to process your personal data at any time.

Withdrawal of the consent is possible solely in the scope of processing performed based on the consent. Polidea is authorised to process your personal data after you withdraw your consent if it has another legal basis for the processing, for the purposes covered by that legal basis.

Categories of recipients:

Your personal data may be shared with:

1)       authorised employees and/or contractors of Polidea

2)       persons or entities providing particular services to Polidea (accounting, legal, IT, marketing and advertising services) – in the scope required for those persons or entities to provide those services to Polidea

 

Retention period:

1)       For the purpose of sending newsletter to the given email address – for as long as the relevant consent is not withdrawn

2)       For statistical, analytical and reporting purposes – for as long as the relevant consent is not withdrawn

Your rights:

 

Used abbreviation:

GDPR – Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016
on the protection of natural persons with regard to the processing of personal data and on the free movement
of such data, and repealing Directive 95/46/EC (General Data Protection Regulation)

According to GDPR, you have the following rights relating to the processing of your personal data, exercised by contacting Polidea via [e-mail, phone].

1)       to access to your personal data (art. 15 GDPR) by requesting sharing and/or sending a copy of all your personal data processed by Polidea

2)       to request rectification of inaccurate personal data
(art. 16 GDPR) by indicating the data requiring rectification

3)       to request erasure of your persona data (art. 17 GDPR); Polidea has the rights to refuse erasing the personal data in specific circumstances provided by law

4)       to request restriction of processing of your personal data (art. 18 GDPR) by indicating the data which should be restricted

5)       to move your personal data (art. 20 GDPR) by requesting preparation and transfer by Polidea of the personal data that you provided to Polidea to you or another controller in a structured, commonly used machine-readable format

6)       to object to processing your personal data conducted based on art. 6.1 e) or f) GDPR, on grounds relating to your particular situation (art. 21 GDPR)

7)       to lodge a complaint with a supervisory authority,
in particular in the EU member state of your habitual residence, place of work or place of the alleged infringement if you consider that the processing
of personal data relating to you infringes the GDPR
(art. 77.1 GDPR)

No obligation to provide data:

Providing your personal data is not obligatory, but necessary for Polidea to provide you the newsletter service

Refusal to provide the above data will result in inability to receive the newsletter service.

Profiling

In the process of providing the newsletter service, we make decisions in an automated way, including profiling, based on the data you provide.

 

“Profiling” means automated processing of personal data consisting of the use of your personal data to evaluate certain personal aspects relating to you, in particular to analyze or predict aspects concerning your personal preferences and interests.

 

The automated decisions are taken based on the analysis of clicked and viewed content. They affect the targeting of specific newsletter content to selected users registered to receive the newsletter service, based on the anticipated interests of the recipient.