The Java Platform Module System (JPMS) is the big new feature of Java 9. Java developers took a long time to develop this JPMS concept because the development of this concept was started in 2005 and in 2017 it came as a Java 9‘s new feature. As a part of jigsaw project, this module programming came in Java 9. We will cover here mainly basic things about JPMS.
Earlier we always talked about jar files but now onwards we have to use a module. A new construct got introduced which is nothing but ‘Module‘.
First let’s talk about what module is?
The module is nothing it is just a group of packages similar to the jar file. The only speciality of the module if we compare it with jar file is that a module can contain configuration information also.
Hence, the module is more powerful than jar file. The configuration information for the module should be specified in a special file named with module-info.java
Every module must contain module-info.java otherwise JVM would not consider it as a module of Java 9.
In Java 9, JDK itself is modularized. All classes of Java 9 are grouped into several modules rather than jar files like:
Java.base module acts as a base for all Java 9 modules. We can find a group of class by using getModule() method.
For example: System.out.println(String.class.getModule());
Need of JPMS:
Application development by using jar-file concept has several serious problems. Let’s discuss about one of the main issue i.e. NoClassDefFoundError.
NoClassDefFoundError: There is no way to specify jar file dependencies until java 8. At runtime if any dependent jar file was missing then in the middle of execution of our program, we would have got NoClassDefFoundError, which is not at all recommended. We will go through with one example to demonstrate this problem.
Now, we will compile all these programs one by one and at last we will run the Test class.
javac -d Demo1.java
javac -d Demo2.java
javac -d Demo3.java
Earlier we always used to talk about jar files but now onwards we have to use a module. A new construct got introduced which is nothing but ‘Module‘. At runtime, by mistake, if pack1 is not available then after executing some part of the code in middle, we will get NoClassDefFoundError.
Now, try to run the Test class.
>> java Test
Output: Test class main
Exception in thread “main” java.lang.NoClassDefFoundError:pack1/Demo1
But in java, there is a way to specify all dependent modules information in module-info.java. If any module is missing then at the beginning only, JVM will identify and won’t start its execution. Hence there is no chance of raising NoClassDefFoundError in the middle of execution.
There exist some more problems with jar file’s concept such as Shadowing Problems etc.
Hope this will help you to understand what modularity actually is. We will come with some more blogs in which we will see how to achieve modularity with examples.