Chapter 4: OpenJDK 21 on Debian, Ubuntu and MX-Linux: Complete Guide.

Advertisement

OpenJDK 21 LTS is the open-source reference implementation of Java SE version 21, following the latest Java ecosystem specifications. This version, which represents the most recent Extended Support (LTS) release, introduces significant improvements in concurrency, performance, security, and modularity, aimed at making it easier to develop and run modern, scalable applications.

OpenJDK 21 It is not included by default in the official Debian 12 and MX Linux 23 repositories, as the default version is still OpenJDK 17. This means that if a user wants to install OpenJDK 21, they must do so manually by downloading the packages from external sources, in https://openjdk.org/.

Availability and Suppliers

OpenJDK 21 It reached general availability in a release planned for September 2023, cementing its position as the preferred platform for developers and system administrators. Production-ready binaries, distributed under the GPL license with the exception of links, are offered by Oracle and other well-known vendors in the community. With this update, OpenJDK 21 replaces previous versions (such as 17), with improvements in all critical areas of software development.

History of OpenJDK and its open source ideologue

OpenJDK has a fascinating history dating back to the efforts of Sun Microsystems, the company that originally developed Java. In 1995Sun released the first version of Java with the motto "Write once, run everywhere," which revolutionized software development. However, in its early years, Java SE was distributed under a proprietary license, which limited its accessibility.

In 2006, Sun Microsystems made the decision to make Java SE open source, which led to the creation of OpenJDK, the official and open source implementation of Java SE. This movement allowed developers from around the world to contribute to the project, fostering innovation and collaboration.

The main creator of Java was James Gosling, who led the development of the language at Sun Microsystems in the 1990s. Initially, Java was called Project Oak, but the name was changed to Java in 1995 Due to trademark issues, Gosling designed Java with a syntax similar to C/C++, but with a focus on portability and security.

In 2010Oracle acquired Sun Microsystems and assumed leadership of OpenJDK, ensuring that it remained the reference implementation of Java SE. Since then, OpenJDK has evolved with new versions and improvements, cementing itself as the preferred choice for Java development in a free and open-source environment.

Highlighted Features

Key new features and improvements in OpenJDK 21 include:

  1. Virtual Threads: New virtual threads allow for lightweight and scalable management of thousands of threads, simplifying concurrent programming for high-performance applications requiring massive scalability ().
  2. Log Patterns and Matching in Switch: Improvements in the record patterns and pattern matching in expressions switchThis makes it easier to write more concise, secure, and readable code by eliminating redundant patterns in handling conditional structures.
  3. Optimized Memory APIMemory handling has been improved through new APIs and low-level optimizations, resulting in improved performance and more efficient resource management in complex applications.
  4. Strengthened Encapsulation and ModularityWith updates to the JDK's modular structure, the encapsulation of internal components has been strengthened. This ensures greater security and stability, allowing developers to work only with the defined public interfaces.
  5. Optimization in AOT and JIT Compilers: Improvements have been implemented in the AOT (Ahead-Of-Time) and JIT (Just-In-Time) compilers, providing faster startups and optimized execution of Java applications.

These features make OpenJDK 21 a modern and robust platform, well-suited for both experimental development and high-demand enterprise applications.

Installing OpenJDK 21

To start enjoying the benefits of OpenJDK 21 on Debian-based systems (including Ubuntu and MX-Linux), follow one of the following methods:

Because MX-Linux 23 comes with OpenJDK 17 by default, you must download OpenJDK 21 from: https://jdk.java.net/21/ going to java version 21 in https://jdk.java.net/archive/ downloading the package .tar.gz

wget https://download.java.net/java/GA/jdk21.0.2/f2283984656d49d69e91c558476027ac/13/GPL/openjdk-21.0.2_linux-x64_bin.tar.gz

It will be downloaded to the directory /Downloads

We created the directory /opt/java :

$ sudo mkdir -p /opt/java

We can extract the downloaded file to get all the files and directories containing OpenJDK and move them to the directory /opt/java :

$ sudo tar xvf openjdk-21.0.2_linux-x64_bin.tar.gz -C /opt/java

To configure the OpenJDK 21 environment, we enter these three environment variables in the terminal:

Advertisement
$ export JAVA_HOME=/opt/java/jdk-21.0.2
$ export PATH=$PATH:$JAVA_HOME/bin
$ export CLASSPATH=.:$JAVA_HOME/lib

Confirms the creation of the variable $JAVA_HOME and the update of PATH and everything went well:

$ echo $JAVA_HOME
/opt/java/jdk-21.0.2
$ echo $PATH
/bin:/opt/Qt/6.5.3/gcc_64/bin:/opt/Qt/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin:/opt/java/jdk-21.0.2/bin

Integration Plugins

Additionally, to integrate OpenJDK 21 with development tools and environments, you can install the following packages:

$ sudo apt install jtreg7 java-package uwsgi-app-integration-plugins

Switch Between Java Versions

To make sure that OpenJDK 21 is displayed, you must verify that it is installed and configured correctly:

// $ sudo update-alternatives --install /usr/bin/java java /opt/java/jdk-21.0.2 2 
$ sudo update-alternatives --install "/usr/bin/java" "java" "/opt/java/jdk-21.0.2/bin/java" 0
$ sudo update-alternatives --install "/usr/bin/javac" "javac" "/opt/java/jdk-21.0.2/bin/javac" 0
$ sudo update-alternatives --set java /usr/lib/jvm/jdk-21.0.2/bin/java
$ sudo update-alternatives --set javac /usr/lib/jvm/jdk-21.0.2/bin/javac

If multiple versions of Java are installed on your system, you can select the default version using:

$ sudo update-alternatives --config java

Existen 4 opciones para la alternativa java (que provee /usr/bin/java).

  Selección   Ruta                                         Prioridad  Estado
------------------------------------------------------------
  0            /usr/lib/jvm/jdk-21.0.7-oracle-x64/bin/java   352378880 modo automático
* 1            /opt/java/jdk-21.0.2/bin/java                 0         modo manual
  2            /usr/lib/jvm/java-17-openjdk-amd64/bin/java   1711      modo manual
  3            /usr/lib/jvm/jdk-21.0.7-oracle-x64/bin/java   352378880 modo manual

Pulse <Intro> para mantener el valor por omisión [*] o pulse un número de selección: 1

When you run it, a list of all installed versions will appear. Simply enter the number corresponding to OpenJDK 21 to set it as the default version.

Installation Verification

To confirm that OpenJDK 21 has been installed correctly and is ready to use, run:

$ java -version
openjdk version "21.0.2" 2024-01-16
OpenJDK Runtime Environment (build 21.0.2+13-58)
OpenJDK 64-Bit Server VM (build 21.0.2+13-58, mixed mode, sharing)

We introduce 2 Java commands, the compiler (javac) and the Java interpreter (Java) to check that they respond on the command line:

// el compilador java
$ javac
Usage: javac <options> <source files>
where possible options include:
  @<filename>                  Read options and filenames from file
  -Akey[=value]                Options to pass to annotation processors
  --add-modules <module>(,<module>)*
        Root modules to resolve in addition to the initial modules,
        or all modules on the module path if <module> is ALL-MODULE-PATH.
  --boot-class-path <path>, -bootclasspath <path>
        Override location of bootstrap class files
  --class-path <path>, -classpath <path>, -cp <path>
        Specify where to find user class files and annotation processors
  -d <directory>               Specify where to place generated class files
  -deprecation
        Output source locations where deprecated APIs are used
  --enable-preview
        Enable preview language features.
        To be used in conjunction with either -source or --release.
  -encoding <encoding>         Specify character encoding used by source files
  -endorseddirs <dirs>         Override location of endorsed standards path
  -extdirs <dirs>              Override location of installed extensions
  -g                           Generate all debugging info
  -g:{lines,vars,source}       Generate only some debugging info
  -g:none                      Generate no debugging info
  -h <directory>
        Specify where to place generated native header files
  --help, -help, -?            Print this help message
  --help-extra, -X             Print help on extra options
  -implicit:{none,class}
        Specify whether to generate class files for implicitly referenced files
  -J<flag>                     Pass <flag> directly to the runtime system
  --limit-modules <module>(,<module>)*
        Limit the universe of observable modules
  --module <module>(,<module>)*, -m <module>(,<module>)*
        Compile only the specified module(s), check timestamps
  --module-path <path>, -p <path>
        Specify where to find application modules
  --module-source-path <module-source-path>
        Specify where to find input source files for multiple modules
  --module-version <version>
        Specify version of modules that are being compiled
  -nowarn                      Generate no warnings
  -parameters
        Generate metadata for reflection on method parameters
  -proc:{none,only,full}
        Control whether annotation processing and/or compilation is done.
  -processor <class1>[,<class2>,<class3>...]
        Names of the annotation processors to run;
        bypasses default discovery process
  --processor-module-path <path>
        Specify a module path where to find annotation processors
  --processor-path <path>, -processorpath <path>
        Specify where to find annotation processors
  -profile <profile>
        Check that API used is available in the specified profile.
        This option is deprecated and may be removed in a future release.
  --release <release>
        Compile for the specified Java SE release.
        Supported releases: 
            8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21
  -s <directory>               Specify where to place generated source files
  --source <release>, -source <release>
        Provide source compatibility with the specified Java SE release.
        Supported releases: 
            8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21
  --source-path <path>, -sourcepath <path>
        Specify where to find input source files
  --system <jdk>|none          Override location of system modules
  --target <release>, -target <release>
        Generate class files suitable for the specified Java SE release.
        Supported releases: 
            8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21
  --upgrade-module-path <path>
        Override location of upgradeable modules
  -verbose                     Output messages about what the compiler is doing
  --version, -version          Version information
  -Werror                      Terminate compilation if warnings occur
// El intérprete java.
$ java
Usage: java [options] <mainclass> [args...]
           (to execute a class)
   or  java [options] -jar <jarfile> [args...]
           (to execute a jar file)
   or  java [options] -m <module>[/<mainclass>] [args...]
       java [options] --module <module>[/<mainclass>] [args...]
           (to execute the main class in a module)
   or  java [options] <sourcefile> [args]
           (to execute a single source-file program)

 Arguments following the main class, source file, -jar <jarfile>,
 -m or --module <module>/<mainclass> are passed as the arguments to
 main class.

 where options include:

    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
    --class-path <class search path of directories and zip/jar files>
                  A : separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -p <module path>
    --module-path <module path>...
                  A : separated list of elements, each element is a file path
                  to a module or a directory containing modules. Each module is either
                  a modular JAR or an exploded-module directory.
    --upgrade-module-path <module path>...
                  A : separated list of elements, each element is a file path
                  to a module or a directory containing modules to replace
                  upgradeable modules in the runtime image. Each module is either
                  a modular JAR or an exploded-module directory.
    --add-modules <module name>[,<module name>...]
                  root modules to resolve in addition to the initial module.
                  <module name> can also be ALL-DEFAULT, ALL-SYSTEM,
                  ALL-MODULE-PATH.
    --enable-native-access <module name>[,<module name>...]
                  modules that are permitted to perform restricted native operations.
                  <module name> can also be ALL-UNNAMED.
    --list-modules
                  list observable modules and exit
    -d <module name>
    --describe-module <module name>
                  describe a module and exit
    --dry-run     create VM and load main class but do not execute main method.
                  The --dry-run option may be useful for validating the
                  command-line options such as the module system configuration.
    --validate-modules
                  validate all modules and exit
                  The --validate-modules option may be useful for finding
                  conflicts and other errors with modules on the module path.
    -D<name>=<value>
                  set a system property
    -verbose:[class|module|gc|jni]
                  enable verbose output for the given subsystem
    -version      print product version to the error stream and exit
    --version     print product version to the output stream and exit
    -showversion  print product version to the error stream and continue
    --show-version
                  print product version to the output stream and continue
    --show-module-resolution
                  show module resolution output during startup
    -? -h -help
                  print this help message to the error stream
    --help        print this help message to the output stream
    -X            print help on extra options to the error stream
    --help-extra  print help on extra options to the output stream
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions with specified granularity
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions with specified granularity
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:jdwp
                  see also -agentlib:jdwp=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
                  HiDPI scaled images are automatically supported and used
                  if available. The unscaled image filename, e.g. image.ext,
                  should always be passed as the argument to the -splash option.
                  The most appropriate scaled image provided will be picked up
                  automatically.
                  See the SplashScreen API documentation for more information
    @argument files
                  one or more argument files containing options
    --disable-@files
                  prevent further argument file expansion
    --enable-preview
                  allow classes to depend on preview features of this release
To specify an argument for a long option, you can use --<name>=<value> or
--<name> <value>.

HelloWorld.java

Here is a simple example in Java 21:

public class HolaMundo {
    public static void main(String[] args) {
        System.out.println("Hola ojosdegato");
    }
}

To compile and run the program, follow these steps:

Save the file HelloWorld.java.

  1. Compile the code: $ javac HolaMundo.java
  2. Run the program: $ java HolaMundo

The output will be:

Hola ojosdegato

Conclusions

With OpenJDK 21 installed on your Debian, Ubuntu, or MX-Linux system, you have a robust and up-to-date environment for developing and running Java applications. This comprehensive guide has taken you from initial installation to environment verification, including practical examples that illustrate the Java 21 development process. Thanks to innovations in concurrency, memory management, and modularity, OpenJDK 21 gives you the tools you need to create modern, secure, and scalable applications.

Explore the official OpenJDK documentation and the Debian and Ubuntu communities to discover even more new features and optimizations that can enhance your Java projects. Also, stay tuned for future updates and improvements that continually enrich the Java ecosystem.

References

EDteam – In Spanish, no one explains it better: I have taken some excellent free courses. They require a 9 to obtain a certificate of achievement. They are very demanding and you learn a lot.

OpenJDK is the free version from the development platform Java in: https://openjdk.org/

Our score
Click to rate this post!
(Votes: 0 Average: 0)
Advertisement
Share on social media...

Deja un comentario

Your email address will not be published. Required fields are marked *

Basic information on data protection
ResponsibleJavier Cachón Garrido +info...
PurposeManage and moderate your comments. +info...
LegitimationConsent of the concerned party. +info...
RecipientsAutomattic Inc., USA to spam filtering. +info...
RightsAccess, rectify and cancel data, as well as some other rights. +info...
Additional informationYou can read additional and detailed information on data protection on our page política de privacidad.

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.

Scroll al inicio

Descubre más desde javiercachon.com

Suscríbete ahora para seguir leyendo y obtener acceso al archivo completo.

Seguir leyendo