Oracle_jre_usage что это за папка? Таинственный FrontCache.
Всем привет. Будем ребята сегодня разговаривать о такой папке как.oracle_jre_usage — я постараюсь узнать максимум информации и вам тут все напишу. В общем отправился я в интернет.. искал инфу, искал, и вот что выяснил. Значит на одном сайте, это сервис вопросов и ответов, так вот там один чел спросил что за папка.oracle_jre_usage и ему сказали что это Java апплеты Oracle. Вы тут можете спросить, но что такое апплет? Это программа, которая не может работать без виртуальной машины Java (JVM). Примерно как-то так =)
Но я стал еще искать инфу по поводу папки.oracle_jre_usage и вот узнал, что в этой папке может быть файл с расширением timestamp. Вот у одного чела в папке был файл 48ac84126bcac2aa.timestamp, хотя расширение вроде как означает временной штамп.. ну мне так показалось…
Обычно папка создается вот в этом месте:
Так, а вот на зарубежном одном сайте нашел инфу что папка.oracle_jre_usage нужна для Java Usage Tracker.
Так ребят, вроде докопался. Значит есть такое как свойства отслеживания Java. И вот это одно из свойств:
Это свойство включает или отключает отслеживание времени последнего использования. Вроде имеется ввиду время, когда JRE использовался для апплета. В общем не совсем понятно, но самое главное не это, а то, что это свойство создает файл в одном из следующих мест (это зависит от операционки):
Правда тут нет такого расположения как C:\Users\Имя\, странно, но может второй вариант это и есть это расположение? Просто папка \Имя\ как раз и похоже на user.home, ибо это личная пользовательская папка, если можно так сказать…
Чтобы легче найти инфу, то там на странице нажмите Ctrl + F и вставьте.oracle_ и потом нажимайте F3 и сразу увидите.
Ну а вот и пример как эта папка выглядит:
Ну а вот что может быть внутри — один файлик с расширением timestamp:
И даже в Windows 10 эта папка может быть:
Теперь по поводу удаления. Нет, я не знаю можно ли удалить, хотя читал что один чел удалял и все было норм. Все равно я советую сделать вот что — не удалять папку, а переименовать, но так, чтобы сохранилось оригинальное имя. Например просто добавьте что-то в конце и потом если будут траблы, то это что-то уберете. Например было.oracle_jre_usage, а вы переименуйте в.oracle_jre_usage_test и все, потом если что, то _test уберете. Я так всегда делаю. Если не захочет переименоваться, будет писать типа файлы в этой папке используются, то даже не знаю что сказать, может папка и нужная.. а можно тогда скачать утилиту Unlocker, и ней переименовать папку.. но это уже совсем другая история..
Ну вот на этом и все ребята! Удачи вам и будьте счастливы!!
11 марта 2013 в 19:41
Таинственный FrontCache
- Java
Всё началось с того, что я в очередной раз ковырял в Eclipse Memory Analyzer дамп памяти Java-приложения и увидел такую интересную вещь:
С кодом HashMap я знаком весьма неплохо, но вложенного класса FrontCache никогда там не видел. Может, с последним обновлением JDK мне прислали обновлённый HashMap? Я заглянул в исходники, но слова «front» там не обнаружилось. Стало интересно, откуда же этот класс берётся и что он делает.
Порывшись в JRE (у меня 1.7u10, но и в последних 1.6 тоже это есть), я нашёл любопытный джарик: alt-rt.jar, в котором и обнаружился HashMap$FrontCache.class, а также несколько других классов (LinkedHashMap, TreeMap, BigDecimal, BigInteger, MutableBigInteger и их вложенные классы). Обычно эти классы подключаются из rt.jar. Почему же они стали грузиться из этого загадочного джарика?
Я вспомнил, что недавно экспериментировал с опциями Java-машины и, в частности, включил -XX:+AggressiveOpts. На сайте Оракла про этот ключ написано скупо:
.oracle_jre_usage что это за папка?
Всем привет. Будем ребята сегодня разговаривать о такой папке как .oracle_jre_usage — я постараюсь узнать максимум информации и вам тут все напишу. В общем отправился я в интернет.. искал инфу, искал, и вот что выяснил. Значит на одном сайте, это сервис вопросов и ответов, так вот там один чел спросил что за папка .oracle_jre_usage и ему сказали что это Java апплеты Oracle. Вы тут можете спросить, но что такое апплет? Это программа, которая не может работать без виртуальной машины Java (JVM). Примерно как-то так
Но я стал еще искать инфу по поводу папки .oracle_jre_usage и вот узнал, что в этой папке может быть файл с расширением timestamp. Вот у одного чела в папке был файл 48ac84126bcac2aa.timestamp, хотя расширение вроде как означает временной штамп.. ну мне так показалось…
Обычно папка создается вот в этом месте:
Так, а вот на зарубежном одном сайте нашел инфу что папка .oracle_jre_usage нужна для Java Usage Tracker.
Так ребят, вроде докопался. Значит есть такое как свойства отслеживания Java. И вот это одно из свойств:
Это свойство включает или отключает отслеживание времени последнего использования. Вроде имеется ввиду время, когда JRE использовался для апплета. В общем не совсем понятно, но самое главное не это, а то, что это свойство создает файл в одном из следующих мест (это зависит от операционки):
Правда тут нет такого расположения как C:\Users\Имя\, странно, но может второй вариант это и есть это расположение? Просто папка \Имя\ как раз и похоже на user.home, ибо это личная пользовательская папка, если можно так сказать…
В общем ребята, вот вам ссылка где можно прочитать о предназначении папки (но все по-английски, если что правой кнопкой и там есть пункт Перевести, это в Хроме):
Чтобы легче найти инфу, то там на странице нажмите Ctrl + F и вставьте .oracle_ и потом нажимайте F3 и сразу увидите.
Ну а вот и пример как эта папка выглядит:
Ну а вот что может быть внутри — один файлик с расширением timestamp:
И даже в Windows 10 эта папка может быть:
Теперь по поводу удаления. Нет, я не знаю можно ли удалить, хотя читал что один чел удалял и все было норм. Все равно я советую сделать вот что — не удалять папку, а переименовать, но так, чтобы сохранилось оригинальное имя. Например просто добавьте что-то в конце и потом если будут траблы, то это что-то уберете. Например было .oracle_jre_usage, а вы переименуйте в .oracle_jre_usage_test и все, потом если что, то _test уберете. Я так всегда делаю. Если не захочет переименоваться, будет писать типа файлы в этой папке используются, то даже не знаю что сказать, может папка и нужная.. а можно тогда скачать утилиту Unlocker, и ней переименовать папку.. но это уже совсем другая история..
Oracle jre usage что это за папка
.oracle_jre_usage что это за папка?
Всем привет. Будем ребята сегодня разговаривать о такой папке как .oracle_jre_usage — я постараюсь узнать максимум информации и вам тут все напишу. В общем отправился я в интернет.. искал инфу, искал, и вот что выяснил. Значит на одном сайте, это сервис вопросов и ответов, так вот там один чел спросил что за папка .oracle_jre_usage и ему сказали что это Java апплеты Oracle. Вы тут можете спросить, но что такое апплет? Это программа, которая не может работать без виртуальной машины Java (JVM). Примерно как-то так
Удалите эти файлы и папки Windows, чтобы освободить место на диске
Лучший способ очистки папок Windows: очистка диска
- Очистка Центра обновления Windows: стирает старые копии файлов Центра обновления Windows. Их можно безопасно удалить в большинстве случаев, но вы должны сохранить их для устранения неполадок, если вы столкнетесь с проблемами, связанными с обновлением.
- Файлы журнала обновления Windows: аналогично, эти файлы данных хранятся в Центре обновления Windows, чтобы помочь вам разобраться в проблемах вокруг них. Вы можете удалить их, если у вас не было ошибок, связанных с обновлением Windows.
- Файлы языковых ресурсов: если вы ранее загрузили другой язык или раскладку клавиатуры, которую вы не используете, это позволит вам легко стереть ее.
- Корзина: Хотя вы можете очистить корзину через ее окно, вы также можете легко сделать это здесь.
- Временные файлы. Как следует из их названия, временные файлы ни для чего не используются в долгосрочной перспективе, поэтому вы можете стереть их, не беспокоясь.
2. Папка Windows Temp
4. Папка Windows.old
6. LiveKernelReports
7. Rempl Папка
Какие папки Windows вы удаляете?
Oracle jre usage что это за папка
Today I installed the latest version of Java SDK (8.0.660.17) for testing purposes. After the installation on the good ol’ XP I noticed that it created a folder named %userprofile%\.oracle_jre_usage. This looked interesting so I googled for it. Turns out lots of people spotted it in earlier version of Java and someone on Oracle forum even provides a good explanation as to what Java component it is from:
That is the default location for the Java Usage Tracker. See the Oracle docs
https://docs.oracle.com/javacomponents/usage-tracker/overview/
Since the folder is created even if the Usage tracker is disabled, we can leverage it as a yet-another-minor timeline-related artifact that can be potentially useful for cherry-picking two Java-related timestamps:
- when Java was installed (more or less, see below)
- when was the last time java.exe was launched (most likely to execute an application; I have not tested JRE & applets yet)
The folder ‘%userprofile%\.oracle_jre_usage’ is created during Java installation:
so you should find at least one randomly named file in this folder. In my case it was:
- 90737d32e3aba4b.timestamp
Inspecting its content shows a path leading to Java JRE and a timestamp in a format that appears to be a Unix timestamp with microseconds:
gives us 1446745410996 which roughly translates to 2015-10-05 09:43:30:996 – somewhere in-between the logs shown in Procmon output (could be a discrepancy between the time of retrieving of the timestamp and time of actually writing it to a file).
Running actual Java program causes the java.exe to look for ‘f9b9f6b8ff8b2b60.timestamp’ (refer to Procmon screenshot above) – this is randomly named file as well so if you look at the folder, you should see 2 of them.
If not found it’s created and its content is similar to ‘90737d32e3aba4b.timestamp’: the path and the Unix stamp.
The following screenshot shows how the Unix timestamp is changing anytime we run java.exe to execute a simple HelloWorld Java application (HelloWorld.class):
To conclude: nothing ground breaking, but yet another pair of timestamps that may help with the investigation one day…
Что такое oracle jre usage
«.oracle_jre_usage» Directory is Created even when Java Usage Tracker is Disabled (Doc ID 2392656.1)
Last updated on APRIL 28, 2021
Applies to:
Symptoms
On Java 8u131 and 8u144 versions, even if tracker is disabled (by default), «.oracle_jre_usage» directory is created in user home directory. This is not the expected behavior.В
If tracker is disabled (by default), «.oracle_jre_usage» directory should not be created in user home directory.
With Java SE 7 versions, «.oracle_jre_usage» is not created.
This issue is not seen using Java 8u51 and 7u79.В
This issue is also observed using Oracle JRE 8u 144-b32 (at time of writing).
Changes
Cause
To view full details, sign in with your My Oracle Support account.
Don’t have a My Oracle Support account? Click to get started!
My Oracle Support provides customers with access to over a million knowledge articles and a vibrant support community of peers and Oracle experts.
Oracle offers a comprehensive and fully integrated stack of cloud applications and platform services. For more information about Oracle (NYSE:ORCL), visit oracle.com. пїЅ Oracle | Contact and Chat | Support | Communities | Connect with us | |
|
| Legal Notices | Terms of Use
Answers
That is the default location for the Java Usage Tracker. See the Oracle docs
As that doc section shows you can create a properties file to enable the tracker and configure the location and contents of the logging.
The tracker has been around since the early Java versions.
The tracker has been around but, but there seems to be some regression in that it now puts this folder there even if you haven’t actually enabled the tracker.
I know that´s a old Question, but I´ve the same problem (on 8 PC´s) and today, finally, I´ve successfully create the properties file and the usagetracker save his log in an other folder.
BUT, this tiresome folder ($HOME/.oracle_jre_usage) appears also, so I think this folder/ timestamp has not to do with the usagetracker.
Is there any people out there how knows something about the folder/ timestamp in my files folder?
I already answered that in my first reply.
If you believe you actually have some ‘problem’ that needs addressed I suggest you create your own thread and post ALL of the info needed to help you. That info would include:
1. the os name and full version
2. the full java version
3. the path and classpath your test uses.
4. the test script or command window commands showing WHAT you do and HOW you do it and that use the path and classpath you provide in step #3
5. the properties file contents and full path and name
6. the contents of the oraclel_jre_usage folder and the folder where you say the log file is created
7. the contents of the log file
I personally do feel this is a PROBLEM.
However that is because I have my custom app environment set up on a removable drive which I use on an ever-changing set of machines, using the concept of «Portable Apps».
Other people may not care, but I certainly do thing that Java should not arbitrarily create files and folders on the host system outside of its own JAVA_HOME environment, and certainly not in the top-level root of my OS’ user directory when there is no good (user opted-in) reason for it.
The Oracle devs and PTB may not consider it a problem either.
I have solved it for myself by adding a line to the batch files that launch all my Java-driven programs, to delete that folder on exit.
Kludgey workaround, but may help others that are also annoyed by this behaviour..
Java Platform, Standard Edition
Java Usage Tracker Guide
Java Usage Tracker tracks how Java Runtime Environments (JREs) are being used in your systems. The output of Java Usage Tracker is a plain text, comma-separated record that contains the JRE version, the application being run, and other details. This record is appended to a file or sent over the network in a User Datagram Protocol (UDP) packet.
Java Usage Tracker System Requirements
Java Usage Tracker is available as part of Oracle Java SE Subscriptions and other legacy products (such as Oracle Java SE Advanced or Oracle Java SE Suite).
Public versions of Java SE 1.4.2, 5.0, and 6 do not support Java Usage Tracker.
Java Usage Tracker Output
The following is an example of output from Java Usage Tracker; it is a record of one invocation of a Java application. Line breaks were added for clarity; each record appears as one line of text:
The following table describes each value of this comma-separated line:
Type of start; it has one of the following values:
VM start : JVM start-up (either Java application or JNI invocation)
javaws application or javaws applet : Java Web Start
The value about the type of start is followed by one of the following values if there is a Deployment Rule Set (DRS) that specifically allows the application to run or block the app.
The value about the type of start is followed by one of the following values if there is no DRS run or block rule:
denied [by security settings]
No value (empty string): The application is allowed to run
Mon Feb 01 14:52:58 PST 2016
Host name and IP address in the form /
Java command (name of main class or jar file) and list of arguments, if any (space-separated list)
Java Web Start applications have the following form:
Applet invocations have the following form:
The values for app_model and app_customer are encoded in Base64.
The value of app_model contains basic information about the application, including location, codebase, and main class. Its value is the same regardless of whether the application is permitted or denied to run.
The parameter app_customer appears only if the application is governed by a specific DRS rule that DRS run rule contains a block.
Directory that contains the JRE ( java.home system property value)
Java version ( java.version system property value)
JVM version ( java.vm.version system property value)
Java vendor ( java.vendor system property value)
JVM vendor ( java.vm.vendor system property value)
Operating system name ( os.name system property value)
Operating system architecture ( os.arch system property value)
Operating system version ( os.version system property value)
JVM arguments (space-separated list); empty if there are no JVM arguments; n/a if this information is not available (for example, in Java SE 1.4.2, this information is not available)
Class path ( java.class.path system property value)
Name=value pairs of any additional system properties specified in the Java Usage Tracker properties file. Multiple pairs are space-separated; empty if no additional property names are specified (default).
Items that Contain Spaces in Java Usage Tracker Output
In the fields that are space-separated lists, a different quote character (by default, the single quotation mark, ‘ ) is used to quote an item that contains a space. Any existing quote characters are printed twice.
For example, consider the following command:
Java Usage Tracker prints these system properties as follows (line breaks were added for clarity):
For JRE versions prior to 8u20, Java Usage Tracker does not surround fields with quotation marks.
Enabling and Configuring Java Usage Tracker
For JRE 8u152 and later, if you want Java Usage Tracker to track all JREs on your system, then put the usagetracker.properties file in the central file system location, which differs depending on your operating system:
Linux and Solaris: /etc/oracle/java/
macOS: /Library/Application Support/Oracle/Java/
If you want Java Usage Tracker to track a specific JRE, then ensure that the usagetracker.properties file doesn’t exist in the central file system location, and put the usagetracker.properties file in the directory /conf/management/ ( /lib/management/ for JRE releases prior to 9). Note that the path name is different, depending on whether you are configuring Java Usage Tracker for a JDK or for a JRE.
The JVM searches the following locations, in order, for a usagetracker.properties file. It uses the first one it finds to enable and configure Java Usage Tracker.
Central file system location (for JRE 8u152 and later)
/conf/management/ ( /lib/management/ for JRE releases prior to 9)
To enable Java Usage Tracker, the usagetracker.properties file that you create must have a valid value for at least one of the following properties:
Java Usage Tracker Properties
This section describes the properties you can specify in the Java Usage Tracker properties file.
These properties are set only in the Java Usage Tracker properties file; they are not set at the command line. This is intended so that Java Usage Tracker has no impact on or interaction with the JRE user or existing applications.
The backslash ( \ ) is an escape character in a properties file. Consequently, when specifying file paths that include directories or drive letters, use a forward slash ( / ) or an escaped backslash ( \\ ) as a directory separator.
Use this property to record values of additional Java properties and their values.
The value of this property is a comma-separated list of properties and their values. For example (ignore line break):
The character or string used to quote items that contain a space in the JVM argument field list and the additional properties field. The default value is the single quotation mark ( ‘ ).
This property is available in JRE 8u20 and later.
The log file size limit, in bytes. If the file size equals or exceeds the given value when logging is attempted, that attempt will be canceled.
If this property is not set, then there is no log file limit.
If this property is specified, the fully qualified path name of the file to which Usage Tracker writes records.
If this property is specified, Java Usage Tracker logs to the specified remote host in a UDP packet. For example (ignore line break):
Specifying an IP address may be faster in some cases; although, this resolution does not delay the startup of the JVM or the application.
See Java Usage Tracker Sample: Receiver for UDP Packets for an example application that can receive UDP packets.
Any single field limit, in bytes. The default is no limit. Java Usage Tracker truncates a field to this limit, without breaking the record format, if the com.oracle.usagetracker.sendTruncatedRecords property is true.
This property is available in JRE 8u152 and later.
Overall record limit, in bytes. The default is no limit. Java Usage Tracker truncates records to this limit if the com.oracle.usagetracker.sendTruncatedRecords property is true.
This property is available in JRE 8u152 and later.
The character or string used to quote fields. The default value is the double quotation mark ( » ).
This property is available in JRE 8u20 and later.
Truncates records and individual fields if they exceed the sizes specified by the com.oracle.usagetracker.maxSize and com.oracle.usagetracker.maxFieldSize properties, respectively. The default value is true.
This property is available in JRE 8u152 and later.
If this property is set to true, error information may be reported to the standard error stream; this is only recommended for diagnostic purposes.
Example Java Usage Tracker properties File
To create a Java Usage Tracker properties file, you can use the following example as a template. Lines that begin with the pound sign (#) are comments.
Java Usage Tracker Sample: Receiver for UDP Packets
The following is an example of running this sample:
Java Usage Tracker Errors and Exceptions
If Java Usage Tracker encounters an error or exception during the logging of a record, it does not interrupt the application currently running.
Java Usage Tracker does not report errors unless the property oracle.usagetracker.verbose is specified in the properties file.
Managing Disk Space Used by Java Usage Tracker Log File
Although the size of the Java Usage Tracker log file is small, consider periodically truncate, compress, archive, or delete the log file. When Java Usage Tracker incrementally adds records to the log file, it does not check for available disk space or perform administrative tasks such as truncating, deleting, or compressing the log file in order to be minimally intrusive.
In addition, you can specify the maximum size of the log file, in bytes, with the oracle.usagetracker.logFileMaxSize property in the properties file.
Java Usage Tracker Limitations
Java Usage Tracker Frequently Asked Questions
Here are answers to some frequently asked questions:
Does Java Usage Tracker affect the private JRE within a JDK, or does it only affect the standalone JRE?
If you have a JDK installed in a computer, there is a JRE in the jre subdirectory; this is the private JRE referred to in the question. Yes, Java Usage Tracker logs the usage of both the private JRE and the standalone JRE, but note that they are configured separately through their own individual conf/management/usagetracker.properties files.
Can Java Usage Tracker log the usage of JDK tools?
If Java Usage Tracker is enabled, it logs the usage of tools that come with the JDK such as jmap and jstack.
Does Java Usage Tracker log the usage of JVMs created by native Java applications?
Yes. When a native application creates a JVM with the Java Native Interface (JNI), Java Usage Tracker logs this invocation with a blank Java command.
Does Oracle capture any of the data logged by Java Usage Tracker?
No. As the administrator of the JRE installation, usage data obtained from Java Usage Tracker is stored in the file of your choice or sent to the UDP host and port that you specify. There is no facility for this data to leave your own network. (Theoretically, if your firewall permits it, the port your UDP host listens on could be configured as remote, but this is not expected or recommended usage.)
What does the log record look like for native applications, applets, and denied applications?
The following is an example of a log record for a native application (line breaks were added for clarity):
The following is an example of a log record for an applet:
The following is an example of a log record of a Java Web Start application that was denied by security settings:
How can I remove the quoting behavior of JRE 8u20 and later for records with the previous formatting?
In the Java Usage Tracker properties file, set blank quote characters with the following two lines:
Documentation Accessibility
For information about Oracle’s commitment to accessibility, visit the Oracle Accessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc.
Access to Oracle Support
Oracle customers that have purchased support have access to electronic support through My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info or visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs if you are hearing impaired.
Java Platform, Standard Edition Java Usage Tracker Guide, Release 1
Copyright © 2014, 2020, Oracle and/or its affiliates.
Describes how to configure, enable, and troubleshoot Java Usage Tracker; interpret its output; and create applications that listen for its data.
This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.
If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, then the following notice is applicable:
U.S. GOVERNMENT END USERS: Oracle programs (including any operating system, integrated software, any programs embedded, installed or activated on delivered hardware, and modifications of such programs) and Oracle computer documentation or other Oracle data delivered to or accessed by U.S. Government end users are «commercial computer software» or “commercial computer software documentation” pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, reproduction, duplication, release, display, disclosure, modification, preparation of derivative works, and/or adaptation of i) Oracle programs (including any operating system, integrated software, any programs embedded, installed or activated on delivered hardware, and modifications of such programs), ii) Oracle computer documentation and/or iii) other Oracle data, is subject to the rights and limitations specified in the license contained in the applicable contract. The terms governing the U.S. Government’s use of Oracle cloud services are defined by the applicable contract for such services. No other rights are granted to the U.S. Government.
This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
Intel and Intel Inside are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Epyc, and the AMD logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.
This software or hardware and documentation may provide access to or information about content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services unless otherwise set forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services, except as set forth in an applicable agreement between you and Oracle.
Установка Oracle Java на Ubuntu и Centos
16 апреля 2019 года компания Oracle изменила лицензию по распространению Java SE. Теперь JRE от Oracle можно использовать бесплатно только для дома, либо при разработке ПО. Это повлекло за собой различные изменения, такие как отсутствие возможности скачать jvm без регистрации на сайте oracle и закрытие основных репозиториев для установки java из пакетов.
Введение
Мне вынужденно пришлось погрузиться в эту тему, потому что на днях требовалось установить Oracle Java JRE 8 на Ubuntu 18 и у меня никак не получалось это сделать. В сети полно инструкций, простых и понятных, как установить Java на Ubuntu 18, но все они разом стали неактуальны. Популярный репозиторий webupd8team/java перешел в статус DISCONTINUED. Выполнить установку из него больше не получится. Будет вот такая ошибка:
Теперь установить Oracle JRE или SDK можно только вручную. Для этого надо:
Установка Oracle Java на Ubuntu
Как я уже сказал выше, для установки oracle java необходимо скачать бинарники. Причем, сделать это так, как я недавно описывал в статье про настройку ELK Stack не получится. Без авторизации ссылки не доступны. Так что необходимо зарегистрироваться на сайте и скачать бинарники себе на компьютер. Я покажу как это сделать на примере Oracle Java 8. Идем на страницу загрузки, авторизовываемся и скачиваем jre-8u211-linux-x64.tar.gz.
Не забудьте отметить флажок напротив Accept License Agreement. После загрузки любым удобным для вас способом скопируйте файл на целевой сервер, куда будем устанавливать Java 8. Я для этого использую scp. Копирую файл в домашнюю директорию /root. Создаем директорию для java и распаковываем туда бинарники.
Java машина должна расположиться в директории /usr/lib/jvm/jre1.8.0_211. Теперь нам необходимо создать символьные ссылки на установленную версию java. Делаем это с помощью update-alternatives.
Зададим переменную JAVA_HOME, которую используют некоторые приложения. Для этого добавляем в файл /etc/environment следующую строку.
Сохраняем его и применяем изменение.
Теперь проверим, что у нас получилось.
Все нормально. В случае, если необходимо обновить или установить другую версию Java, то все проделывается точно так же, только в конце указываются ссылки на новую директорию с Java.
В принципе, на этом с установкой Oracle Java на Ubuntu все. В общем случае выполнено все необходимое. Но я в процессе компиляции одного приложения столкнулся с одной ошибкой. Расскажу вам, как ее решил.
Could not find tools.jar
Приложение использовало систему автоматической сборки gradle, которая прекращала сборку с ошибкой.
Я долго гуглил решение. В общем случае оно состоит в том, что нужно тем или иным образом явно указать путь к tools.jar, но у меня этого файла вообще не было в системе и я не знал, где его взять. Я вообще не разбираюсь в теме с явой, первый раз собирал приложение сам. Вышел из положения в итоге следующим образом. Я установил openjdk-8-jdk следующей командой.
Она установилась в директорию /usr/lib/jvm/java-8-openjdk-amd64. Там в директории libs лежал файл tools.jar. Я просто скопировал его в /usr/lib/jvm/jre1.8.0_211/lib, где установлена oracle java. После этого сборка прошла без ошибок.
Уже после написания статьи понял, что мне нужно было установить не Oracle JRE, а JDK, тогда бы все сразу собралось без ошибок. Надеюсь эта информация будет полезна тем, кто будет искать решение похожей проблемы. Она возникла из-за недопонимания различий между JRE и JDK.
Что такое Oracle JRE и JDK и в чем отличие?
Моя первоначальная суета вокруг установки и компиляции Java приложений была связана с тем, что я не обратил внимание на то, что существуют 2 совершенно разных пакета для установки Java.
Подробнее об этих продуктах и об отличиях JRE и SDK можно почитать на официальном сайте в faq. Таким образом, если вам необходимо только запускать уже скомпилированные java приложения, достаточно пакета JRE. Если вам нужно собрать из исходников java программу, ставьте SDK. Я с этим разобрался только в момент написания этой статьи, так что изложение получилось не очень последовательным.
Установка Oracle Java на Centos
Установить Java SE Runtime Environment на CentOS по прежнему не сложно, так как есть готовый rpm пакет. Единственное неудобство, его нужно вручную скачивать с сайта и передавать на сервер. Для скачивания нужно зарегистрироваться на сайте oracle.com. После авторизации, необходимо сходить в раздел загрузки и скачать rpm пакет.
После этого передаем его на целевой сервер и устанавливаем Oracle Java на CentOS следующей командой:
После этого можно проверить версию Java в консоли.
На этом установка Oracle Java на Centos закончена.
Заключение
Перед установкой Oracle Java не забывайте, что теперь ее нельзя просто так использовать в коммерческой среде. Придется платить, если нужна лицензионная чистота. Думаю, что в ближайшее время все проекты постараются отладить свою работу под бесплатным OpenJDK. Число клиентов Oracle JRE явно убавится в разы.
Для меня остается не понятен момент с работой Java на Windows. Она требуется для кучи всевозможных сервисов и оборудования. По идее, теперь за ее использование нужно платить. Как быть со всякими старыми железками, к которым обновлений уже не будет? Что думаете по этому поводу?