Java Platform Module System or JPMS was introduced in Java 9 as a form of encapsulation package.
A module is a group of one or more packages and a module-info.java
file that contain its metadata.
In other words it consists in a ‘package of packages‘.
Benefits of using modules:
While using modules in a Java 9+ application is optional, there are a series of benefits from using them:
-
Better access control: Creates a fifth level of class access control that restricts packages to be available to outer code. Packages that are not explicitly exposed through
module-info
will be not available on modules external code. This is useful for encapsulation that allows to have truly internal packages. -
Clear dependency management: Application’s dependencies will be specified in
module-info.java
file. This allows us to clearly identify which are the required modules/libraries. -
Custom java builds: JPMS allow developers to specify what modules are needed. This makes it possible to create smaller runtime images discarding JRE modules that the application doesn’t need (AWT, JNI, ImageIO…).
-
Performances improvements: Having an static list of required modules and dependencies at start-up allows JVM to reduce load time and memory footprint because it allows the JVM which classes must be loaded from the beginning.
-
Unique package enforcement: A package is allowed to be supplied by only one module. JPMS prevents JAR hell scenarios such as having multiple library versions in the classpath.
The main counterpart is not all libraries have module support and, while it is possible it also makes more difficult to switch to a modular code that depends on this kind of libraries. For example, libraries that make an extensive use of reflection will need an extra configuration step because JPMS cannot identify and load classes at runtime.