Starting with Java 9, modularization with Project Jigsaw makes it easy to create lightweight JREs for distribution. Lightweight JREs contain only the bare essentials that your application uses, so you can keep your file size very small. Therefore, it is an essential support when bundling JRE with an application.
This article describes how to make a lightweight JRE.
First, get OpenJDK.
This time, I used the latest stabilizer OpenJDK 11 as of 02/08/2019. I will.
When the ZIP file is expanded, the folder structure is as follows.
jdk-11
├─ bin
├─ conf
├─ include
├─ jmods
├─ legal
├─ lib
└─ release
Use the bin
and jmods
folders to generate a lightweight JRE.
Check the dependencies of the packages used by the application (jar file) with the jdeps
command contained in the jdk-11 / bin
folder. (You can also specify it with a wildcard like * .jar)
cd jdk-11\bin
jdeps.exe --list-deps --ignore-missing-deps C:\example\app.jar
When you run the command, you will see a list of packages used by that application. You can see that the ʻapp.jar` example above depends on the following packages:
java.base
java.desktop
java.logging
java.sql
java.xml
In other words, if at least these packages are included in the JRE to run the application, it will be a Java runtime environment.
Now that we have a list of packages used by our application with the jdeps
command, we will generate a JRE that contains only these packages.
To generate a JRE, just pass the required packages to the jlink
command.
When passing multiple packages, separate them with commas.
jlink.exe --compress=2 --module-path ..\jmods --add-modules java.base,java.desktop,java.logging,java.sql,java.xml --output jre
When you run the command, a jre
folder will be created in the current folder.
This generated folder is a lightweight JRE.
All you have to do now is use this lightweight JRE as your application's Java runtime environment. It can be used without any problem as long as it does not depend on the new package due to modification on the application side.
The following results were obtained when comparing the file sizes of the original version
of OpenJDK 11 and the lightweight version
of the JRE containing only a specific package [^ 1].
Original version | Lightweight version |
---|---|
299M | 46M |
The lightweight version of JRE contains only the minimum required packages for your application, so the file size is kept small.
Due to the large file size differences, it is recommended that you generate a lightweight JRE before bundling it with your application.
Recommended Posts