- How to install Java 8 and 11 on Red Hat Enterprise Linux 8
- TL; DR
- Watch the Video
- The Longer Version.
- Finding available Java packages
- Switching Java Versions
- Selecting Java Versions with Alternatives
- Switching alternatives non-interactively
- Selecting Java Versions by Setting JAVA_HOME
- Hello World on Steroids, JDK 11 Style
- linux-notes.org
- Установка OpenJDK 7 на CentOS/RHEL/Fedora
- Установка OpenJDK 6 на CentOS/RHEL/Fedora
- Установка Oracle Java 8 на CentOS/RHEL/Fedora
- Настройка JAVA (JDK) на CentOS/RHEL/Fedora
- Red Hat Customer Portal
- Log in to Your Red Hat Account
- Red Hat Account
- Customer Portal
- Select Your Language
- Chapter 2. Installing OpenJDK 8 on Red Hat Enterprise Linux
- 2.1. Installing a JRE on RHEL using yum
- 2.2. Installing a JRE on RHEL using an archive
- 2.3. Installing OpenJDK 8 on RHEL using yum
- 2.4. Installing OpenJDK on RHEL using an archive
- 2.5. Installing multiple major versions of OpenJDK on RHEL using yum
- 2.6. Installing multiple major versions of OpenJDK on RHEL using an archive
- 2.7. Installing multiple minor versions of OpenJDK on RHEL using yum
- 2.8. Installing multiple minor versions of OpenJDK on RHEL using an archive
How to install Java 8 and 11 on Red Hat Enterprise Linux 8
With Red Hat Enterprise Linux (RHEL) 8, two major versions of Java will be supported: Java 8 and Java 11. In this article, I’ll refer to Java 8 as JDK (Java Development Kit) 8 since we are focusing on the development aspect of using Java. JDK 8 and JDK 11 refer to Red Hat builds of OpenJDK 8 and OpenJDK 11 respectively. Through this article, you’ll learn how to install and run simple Java applications on RHEL 8, how to switch between two parallel installed major JDK versions via alternatives and how to select one of the two JDKs on a per-application basis.
TL; DR
To install JDK 8, use: (If you didn’t select Make this user administrator during install see this article to enable sudo on RHEL)
Then run Java “Hello World” as follows:
To instal JDK 11, use:
Then run Java “Hello World” as follows:
Yes, with JDK 11 you can directly run Java source files. The compilation step is handled for you.
Watch the Video
If you prefer to watch a short 4 minute demo video, here it is:
The Longer Version.
Let’s consider we have a freshly commissioned Red Hat Enterprise Linux 8 machine and we’d like to use it for running Java applications.
Finding available Java packages
In order to figure out which RPM packages to install, we can ask the packaging system which ones provide the java binary:
This command tells us that packages java-1.8.0-openjdk-headless and java-11-openjdk-headless both provide the java binary. For the purpose of this article, we’re interested in the development kits, so we’ll install the -devel sub-packages instead. The -devel packages will pull in -headless packages as a dependency. If you already know that RHEL packages are OpenJDK builds, yum list available might be useful too:
For the purpose of this article, we are going to install JDK 8 and JDK 11 in parallel, and also install maven:
Switching Java Versions
In the previous step, we installed JDK 8 and JDK 11 in parallel. At this point in time, JDK 8 is the main JDK on RHEL 8. That’s why you get this output when running java -version on a fresh RHEL 8 install:
There are two ways to select the Java version you want:
- Switch java and javac binaries system wide via alternatives. This approach requires root privileges.
- Select the JDK on a per-application basis by setting JAVA_HOME
Selecting Java Versions with Alternatives
java and javac binaries on RHEL 8 are managed by the alternatives system. This means a system administrator can switch the system java (or javac ) to be something other than the default, JDK 8. The alternatives system uses priorities in order to determine which JDK should be available via /usr/bin/java . JDK 8 has been given a higher priority on RHEL-8 than JDK 11. But we are getting ahead of ourselves. First, lets see which binaries are managed by alternatives:
We see that java and javac are managed by alternatives. Next, we are going to switch to JDK 11, using the alternatives —config command:
This will switch the system java binary to JDK 11. We do the same for javac since java and javac are independently managed. There is no need to switch anything else as every other JDK binary will switch either with the java or the javac binary:
Switching alternatives non-interactively
Here is an approach to switch to JDK 11, via alternatives, using non-interactive means, which comes in handy if you need to script it:
Similarly, switching to JDK 8 via alternatives by non-interactive means:
A similar approach can be followed for javac .
Selecting Java Versions by Setting JAVA_HOME
Many applications support using the JAVA_HOME environment variable, as a way to specify which JDK should be used to run the application. The examples below demonstrate this usage when running maven. This approach is handy if you don’t have root privileges, but both JDKs are already installed on your system.
Selecting JDK 8:
Selecting JDK 11:
This feature also comes in handy if you have multiple minor JDK versions installed as Leo Ufimtsev described in his article for RHEL 7.
Hello World on Steroids, JDK 11 Style
With JEP 330, part of JDK 11, it’s now possible to run Java code in a script-like fashion. The feature is called “Launch Single-File Source-Code Programs” and allows one to use Java as scripting language. Here is a simple example:
Thank you. I hope you’ve found this article useful.
Источник
linux-notes.org
Данная статья посвящается установке Java на CentOS, Fedora и RHEL. Java — популярная программная платформа, которая позволяет запускать Java-приложения и апплеты.
Рассматриваются следующие версии Java:
- Установка OpenJDK 7 на CentOS/RHEL/Fedora
- Установка OpenJDK 6 на CentOS/RHEL/Fedora
- Установка Oracle Java 8 на CentOS/RHEL/Fedora
- Установка Oracle Java 7 на CentOS/RHEL/Fedora
Все действия будут осуществляться от обычного пользователя без полномочий root с привилегиями sudo.
Существует три различных версии платформы Java:
- Standard Edition (SE).
- Enterprise Edition (EE).
- Micro Edition (ME).
Данная статья ориентирована на Java SE (Java Platform, Standard Edition). Существует два различных пакета Java SE, которые могут быть установлены:
- Java Runtime Environment (JRE).
- Java Development Kit (JDK).
JRE — это реализация виртуальной машины Java (JVM), которая позволяет запускать откомпилированные Java-приложения и апплеты. JDK включает JRE и другое программное обеспечение, которое требуется для написания, разработки и компиляции Java-приложений и апплетов.
Есть также две различные реализации Java:
Обе реализации основаны в основном на одном коде, но OpenJDK, эталонная реализация Java, является полностью с открытым исходным кодом, а Oracle Java содержит некоторый проприетарный код. Большинство Java-приложений будут работать нормально, но вы должны использовать ту реализацию, которое требует ваша реализация кода.
Установка OpenJDK 7 на CentOS/RHEL/Fedora
В этом разделе будет показано, как установить предварительно установленные пакеты OpenJDK 7 JRE и JDK с помощью пакетного менеджера — yum.
Чтобы установить OpenJDK 7 JRE используя yum, выполните:
Чтобы установить OpenJDK 7 JDK используя yum, выполните:
Поздравляю! Вы установили OpenJDK 7 JDK и OpenJDK 7 JRE.
Установка OpenJDK 6 на CentOS/RHEL/Fedora
В этом разделе будет показано, как установить предварительно установленные пакеты OpenJDK 7 JRE и JDK с помощью пакетного менеджера — yum.
Чтобы установить OpenJDK 7 JRE используя yum, выполните:
Чтобы установить OpenJDK 7 JDK используя yum, выполните:
Поздравляю! Вы установили OpenJDK 6 JDK и OpenJDK 6 JRE.
Установка Oracle Java 8 на CentOS/RHEL/Fedora
Примечание. Если вы хотите установить другую версию Oracle Java 8 JRE, перейдите на страницу загрузки Java. Выберете Java 8 JRE, примите лицензионное соглашение и скопируйте ссылку загрузки соответствующего пакета .rpm.
Перейдем в папку и загрузим Oracle Java 8 JDK с помощью следующих команд:
Затем установите RPM с помощью команды yum (если вы скачали другую версию, замените имя файла здесь):
Теперь Java должна быть установлена по адресу: /usr/java/jdk1.8.0_131/jdk/bin/java, и связана с /usr/bin/java.
PS: Версии всегда меняются и может буть уже не актуальны! Так же, ссылки что выше имеют такую же ситуацию.
Вы можете удалить архив, который вы скачали ранее:
Перейдем в папку и загрузим Oracle Java 8 JRE с помощью следующих команд:
Затем установите RPM с помощью команды yum (если вы скачали другую версию, замените имя файла здесь):
Теперь Java должна быть установлена по адресу:/usr/java/jre1.8.0_121/jre/bin/java, и связана с /usr/bin/java.
Вы можете удалить архив, который вы скачали ранее:
И так, Oracle Java 8 JDK Oracle Java 8 JRE установлены
Настройка JAVA (JDK) на CentOS/RHEL/Fedora
Проверка версии Java
Проверяем установленную версию JDK на системе, используя команду:
Настройка переменных среды (ENV)
Мы можем легко установить переменное окружение, используя команду export, как показано ниже.
Теперь давайте проверим что поулчилось, используя команды:
Или, проверим полный PATH:
Однако, вышеуказанный метод не рекомендуется. Потому что PATH будет удален при перезагрузки системы. Чтобы сделать его постоянным, вы должны добавить пути в профиль системы.
Для этого создайте файл java.sh в /etc/profile.d/ каталоге:
И прописываем в него:
Сохраняем и закрываем файл. После чего, ножно сделать его исполняемым:
Затем, перечитаем файл:
PS: Можно этого не делать — а сделать следующее…..
Чтобы все настройки вступили в силу, выполняем:
Что, если я не удалю старые версии JDK из моей системы?
Убедитесь, что вы удалили все старые версии JDK из вашей системы. Если вы не удаляли более старые версии с вашего сервера перед установкой последней версии JDK, вы должны сообщить вашей системе, откуда должна выполняться java.
По умолчанию JDK 1.8.x будет установлен в /usr/java/jdk1.8.0_121/. Чтобы рассказать о нашей системе, откуда должна выполняться java, нам нужно запустить следующие команды один за другим:
Все сделано. Давайте проверим альтернативы:
ИЛИ, более правильный вариант — это выполнить команду:
И настраиваем кто будет использоваться!
Вот и все! Статья «Установка JAVA (JDK) на CentOS/RHEL/Fedora» завершена.
Источник
Red Hat Customer Portal
Log in to Your Red Hat Account
Your Red Hat account gives you access to your profile, preferences, and services, depending on your status.
If you are a new customer, register now for access to product evaluations and purchasing capabilities.
Need access to an account?
If your company has an existing Red Hat account, your organization administrator can grant you access.
Red Hat Account
Customer Portal
For your security, if you’re on a public computer and have finished using your Red Hat services, please be sure to log out.
Select Your Language
Chapter 2. Installing OpenJDK 8 on Red Hat Enterprise Linux
OpenJDK is an environment for developing and running a wide range of platform-agnostic applications, from mobile applications to desktop and web applications and enterprise systems. Red Hat provides an open source implementation of the Java Platform SE (Standard Edition) called OpenJDK.
Applications are developed using the JDK (Java Development Kit). Applications are run on a JVM (Java Virtual Machine), which is included in the JRE (Java Runtime Environment) and the JDK. There is also a headless version of Java which has the smallest footprint and does not include the libraries needed for a user interface. The headless version is packaged in the headless subpackage.
If you are unsure whether you need the JRE or the JDK, it is recommended that you install the JDK.
The following sections provide instructions for installing OpenJDK on Red Hat Enterprise Linux:
2.1. Installing a JRE on RHEL using yum
You can install OpenJDK Java Runtime Environment (JRE) using the system package manager, yum .
Prequisites
- Log in as a user with root privileges.
Procedure
Run the yum command, specifying the package you want to install:
$ sudo yum install java-1.8.0-openjdk
Check that the installation works:
2.2. Installing a JRE on RHEL using an archive
You can install OpenJDK Java Runtime Environment (JRE) using an archive. This is useful if the Java administrator does not have root privileges.
To ease the upgrades for later versions create a parent directory to contain your JREs and create a symbolic link to the latest JRE using a generic path.
Procedure
Extract the contents of the archive to a directory of your choice:
Create a generic path by using symbolic links to your JRE for easier upgrades:
Configure the JAVA_HOME environment variable:
Verify that JAVA_HOME environment variable is set correctly:
When installed using this method, OpenJDK will only be available for the current user.
Add the bin directory of the generic JRE path to the PATH environment variable:
Verify that java -version works without supplying the full path:
You can ensure that JAVA_HOME environment variable persists for the current user by exporting the environment variable in
2.3. Installing OpenJDK 8 on RHEL using yum
You can install OpenJDK using the system package manager, yum .
Prerequisites
- Log in as a user with root privileges.
Procedure
Run the yum command, specifying the package you want to install:
$ sudo yum install java-1.8.0-openjdk-devel
Check that the installation works:
2.4. Installing OpenJDK on RHEL using an archive
You can install OpenJDK using an archive. This is useful if the Java administrator does not have root privileges.
To ease upgrades, create a parent directory to contain your JREs and create a symbolic link to the latest JRE using a generic path.
Procedure
Extract the contents of the archvie to a directory of your choice:
Create a generic path by using symbolic links to your JRE for easier upgrades:
Configure the JAVA_HOME environment variable:
Verify that JAVA_HOME environment variable is set correctly:
When installed using this method, OpenJDK will only be available for the current user.
Add the bin directory of the generic OpenJDK path to the PATH environment variable:
Verify that javac -version works without supplying the full path:
You can ensure that JAVA_HOME environment variable persists for the current user by exporting the environment variable in
2.5. Installing multiple major versions of OpenJDK on RHEL using yum
You can install multiple versions of OpenJDK using the system package manager, yum .
Prerequisites
- A Red Hat Subscription Manager (RHSM) account with an active subscription that provides access to a repository that provides the OpenJDK versions you want to install.
- You must have root privileges on the system.
Procedure
Run the following yum commands to install the package:
$ sudo yum install java-1.8.0-openjdk
$ sudo yum install java-11-openjdk
After installing, check the available java versions:
Check the current java version:
Additional resources
- You can configure the default OpenJDK version to use by using java —alternatives . For more information see Selecting a system-wide java version.
2.6. Installing multiple major versions of OpenJDK on RHEL using an archive
You can install multiple major versions of OpenJDK by using the same procedures found in Installing a JRE on RHEL using an archive or Installing OpenJDK on RHEL using an archive using multiple major versions.
For instructions how to configure the default OpenJDK version for the system, see Selecting a system-wide archive java version.
2.7. Installing multiple minor versions of OpenJDK on RHEL using yum
You can install multiple minor versions of OpenJDK on RHEL. This is done by preventing the installed minor versions from being updated.
Procedure
Add the installonlypkgs option in /etc/yum.conf to specify the OpenJDK packages that yum can install but not update.
installonlypkgs=java- —openjdk,java- —openjdk-headless,java- —openjdk-devel
Updates will install new packages while leaving the old versions on the system:
The different minor versions of OpenJDK can be found in the /usr/lib/jvm/ files.
For example, the following shows part of /usr/lib/jvm/java-1.8.0-openjdk-1.8.0 :
2.8. Installing multiple minor versions of OpenJDK on RHEL using an archive
Installing multiple minor versions is the same as Installing a JRE on RHEL using an archive or Installing OpenJDK on RHEL using an archive using multiple minor versions.
For instructions how to choose a default minor version for the system, see Selecting a system-wide archive java version.
Источник