Java 9 — modularity

For the really busy, for those who just want the headlines, for the ones with short attention span, here it is, the TL;DR version of what’s new in Java 9 in byte size (see what I did there?)

Jigsaw, modularity

Create a file

Add the module keyword, followed by the name of the module and a set of brackets.

module com.ricardoespsanto {}

Module is not a reserved keyword. The file will be compiled into a .class file but it does not provide any interactive functionality from a programmatic point of view.

By default all code inside a module is encapsulated. So we are not exposing anything to the outside world with this vanilla, empty module declaration.

Modules can depend on each other — use the requires keyword for it.

module com.ricardoespsanto {
 requires com.ricardoespsanto.otherModule;

Of course the otherModule has to expose what it wants to share to the outside world. For that we use the exports keyword followed by a package name. {
exports com.ricardoespsanto.aPackageName;

Compile it using javac but with a new flag: modulesourcepath

javac -modulesourcepath src -d out $(find . -name ‘*.java’)

Run it by using the new mp flag which stands for module path and is very similar to what cp or class path does and the new m flag which indicates the module that we wish to ‘start’

java -mp out -m com.ricardoespsanto/

Great we got it running but what’s the point of modularity at this level if we still have to know implementation details to use other modules?

AnInterface theInstance = new Implementation();

We don’t. The java fairies have though of that too. There’s something called services which we can use to describe how and from where do we intend to consume services’ implementations.

module consumer {
 requires anAPI;
 uses com.api.aService;
module provider {
 requires anAPI;
 provides com.api.aService with provider.aServiceImpl;

The consumer uses the ServiceLoader API to use the aServiceImpl

Iterable<AService> aServices = ServiceLoader.load(AService.class);
for (AService aService: aServices){

Now that we have modules and that the modules don’t necessarily need to know about each other’s details. It would be really nice if we could release it all under one bundle.

Well that’s where linking comes into play. There’s a new tool called jlink in JDK 9 and it takes a bunch of arguments and possible combinations but in short it can create an image which can be platform independent and self sustainable to be executed anywhere.

Jlink greatly reduces the amount of parameters and invocations one needs to setup or remember in order to run simple java applications.

Stay tuned for the rest of the Java 9 series and if this post was of any interest to you please hit that like or subscribe button.