Java runtime environment что это
Перейти к содержимому

Java runtime environment что это

  • автор:

Java™ Platform Overview

The JRE provides the libraries, Java virtual machine, and other components necessary for you to run applets and applications written in the Java programming language. This runtime environment can be redistributed with applications to make them free-standing.

Java SE Development Kit (JDK)

The JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.

Java Programming Language

The Java Programming Language is a general-purpose, concurrent, strongly typed, class-based object-oriented language. It is normally compiled to the bytecode instruction set and binary format defined in the Java Virtual Machine Specification. For more information see Language Features.

Java Virtual Machines

The Java virtual machine is an abstract computing machine that has an instruction set and manipulates memory at run time. The Java virtual machine is ported to different platforms to provide hardware- and operating system-independence.

The Java Platform, Standard Edition provides two implementations of the Java virtual machine (VM):

Java HotSpot Client VM

The client VM is an implementation for platforms typically used for client applications. The client VM is tuned for reducing start-up time and memory footprint. It can be invoked by using the -client command-line option when launching an application.

Java HotSpot Server VM

The server VM is an implementation designed for maximum program execution speed, trading off launch time and memory. It can be invoked by using the -server command-line option when launching an application.

For more information, see the VM documentation.

Base Libraries

Classes and interfaces that provide basic features and fundamental functionality for the Java platform.

Lang and Util Packages

Provides the fundamental Object and Class classes, wrapper classes for primitive types, a basic math class, and more. See the Lang and Util documentation for more information.

Math functionality includes floating point libraries and arbitrary-precision math. For more information, see the Math documentation.

Monitoring and Management

Comprehensive monitoring and management support for Java platform including Monitoring and Management API for Java virtual machine, Monitoring and Management API for the Logging Facility, jconsole and other monitoring utilities, out-of-the-box monitoring and management, Java Management Extensions (JMX), and Oracle’s Platform Extension. See the Monitoring and Management documentation for more information.

Package Version Identification

The package versioning feature enables package-level version control so that applications and applets can identify at runtime the version of a specific Java Runtime Environment, VM, and class package. For more information, see the Package Version Identification documentation.

Reference Objects

Reference objects support a limited degree of interaction with the garbage collector. A program may use a reference object to maintain a reference to some other object in such a way that the latter object may still be reclaimed by the collector. A program may also arrange to be notified some time after the collector has determined that the reachability of a given object has changed. Reference objects are therefore useful for building simple caches as well as caches that are flushed when memory runs low, for implementing mappings that do not prevent their keys (or values) from being reclaimed, and for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism. For more information, see the Reference Objects documentation.

Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class. Programs can suppress default reflective access control. For more information, see the Reflection documentation.

Collections Framework

A collection is an object that represents a group of objects. The collections framework is a unified architecture for representing collections, allowing them to be manipulated independently of the details of their representation. It reduces programming effort while increasing performance. It allows for interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software reuse. For more information, see the Collections Framework documentation.

Concurrency Utilities

The Concurrency Utilities packages provide a powerful, extensible framework of high-performance threading utilities such as thread pools and blocking queues. This package frees the programmer from the need to craft these utilities by hand, in much the same manner the Collections Framework did for data structures. Additionally, these packages provide low-level primitives for advanced concurrent programming. For more information, See the Concurrency Utilities documentation.

Java Archive (JAR) Files

JAR (Java Archive) is a platform-independent file format that aggregates many files into one. Multiple Java applets and their requisite components (.class files, images and sounds) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction, greatly improving the download speed. The JAR format also supports compression, which reduces the file size, further improving the download time. In addition, the applet author can digitally sign individual entries in a JAR file to authenticate their origin. It is fully extensible. For more information, see the Java Archive documentation.

The Logging APIs facilitate software servicing and maintenance at customer sites by producing log reports suitable for analysis by end users, system administrators, field service engineers, and software development teams. The Logging APIs capture information such as security failures, configuration errors, performance bottlenecks, and/or bugs in the application or platform. For more information, see the Logging documentation.

Preferences

The Preferences API provides a way for applications to store and retrieve user and system preference and configuration data. The data is stored persistently in an implementation-dependent backing store. There are two separate trees of preference nodes, one for user preferences and one for system preferences. For more information, see the Preferences API documentation,

Other Base Packages

The java.io and java.nio packages provide a rich set of APIs for managing an application’s I/O. The functionality includes file and device I/O, object serialization, buffer management, and character-set support. Additionally, the APIs support features for scalable servers including multiplexed, non-blocking I/O, memory mapping and locks for files. For more information, see the I/O documentation.

Object Serialization

Object Serialization extends the core Java Input/Output classes with support for objects. Object Serialization supports the encoding of objects, and the objects reachable from them, into a stream of bytes; and it supports the complementary reconstruction of the object graph from the stream. Serialization is used for lightweight persistence and for communication via sockets or Remote Method Invocation (RMI). See the Object Serialization documentation for more information.

Provides classes for networking functionality, including addressing, classes for using URLs and URIs, socket classes for connecting to servers, networking security functionality, and more. See the Networking documentation for more information.

APIs for security-related functionality such as configurable access control, digital signing, authentication and authorization, cryptography, secure Internet communication, and more. See the Security documentation for more information.

Internationalization

APIs that enable the development of internationalized applications. Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes. See the Internationalization documentation for more information.

JavaBeans™ Component API

Contains classes related to developing beans — components based on the JavaBeans™ architecture that can be pieced together as part of developing an application. See the JavaBeans documentation for more information.

Java Management Extensions (JMX)

The Java Management Extensions (JMX) API is a standard API for management and monitoring of resources such as applications, devices, services, and the Java virtual machine. Typical uses include consulting and changing application configuration, accumulating statistics about application behavior, and notifying of state changes and erroneous conditions. The JMX API includes remote access, so a remote management program can interact with a running application for these purposes. See the Java Management Extensions documentation for more information.

The Java platform provides a rich set of APIs for processing XML documents and data. See the Java SE XML documentation for more information.

Java Native Interface (JNI)

Java Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the Java virtual machine into native applications. The primary goal is binary compatibility of native method libraries across all Java virtual machine implementations on a given platform. See the Java Native Interface documentation for more information.

Extension Mechanism

Optional packages are packages of Java classes (and any associated native code) that application developers can use to extend the functionality of the core platform. The extension mechanism allows the Java virtual machine (VM) to use the classes of the optional extension in much the same way as the VM uses classes in the Java Platform. The extension mechanism also provides a way for needed optional packages to be retrieved from specified URLs when they are not already installed in the JDK or Runtime Environment. See the Java Extension Mechanism documentation for more information.

Endorsed Standards Override Mechanism

An endorsed standard is a Java API defined through a standards process other than the Java Community ProcessSM (JCP). Because endorsed standards are defined outside the JCP, it is anticipated that such standards may be revised between releases of the Java Platform. In order to take advantage of new revisions to endorsed standards, developers and software vendors may use the Endorsed Standards Override Mechanism to provide newer versions of an endorsed standard than those included in the Java Platform as released by Oracle. See the Endorsed Standards Override Mechanism documentation for more information.

Integration Libraries

Java Database Connectivity (JDBC) API

The JDBC™ API provides universal data access from the Java programming language. Using the JDBC 3.0 API, you developers can write applications that can access virtually any data source, from relational databases to spreadsheets and flat files. JDBC technology also provides a common base on which tools and alternate interfaces can be built. For more information, see the JDBC documentation.

Remote Method Invocation (RMI)

Remote Method Invocation (RMI) enables the development of distributed applications by providing for remote communication between programs written in the Java programming language. RMI enables an object running in one Java Virtual Machine to invoke methods on an object running in another Java VM, which may be on a different host. For more information, see the Java SE RMI documentation.

Java IDL (CORBA)

Java IDL technology adds CORBA (Common Object Request Broker Architecture) capability to the Java platform, providing standards-based interoperability and connectivity. Java IDL enables distributed Web-enabled Java applications to transparently invoke operations on remote network services using the industry standard IDL (Object Management Group Interface Definition Language) and IIOP (Internet Inter-ORB Protocol) defined by the Object Management Group. Runtime components include a Java ORB for distributed computing using IIOP communication. For more information, see the Java IDL documentation.

RMI-IIOP

Java Remote Method Invocation over Internet Inter-ORB Protocol technology The RMI Programming Model enables the programming of CORBA servers and applications via the RMI API. You can choose to work completely within the Java programming language using the Java Remote Method Protocol (JRMP) as the transport, or work with other CORBA-compliant programming languages using the Internet InterORB Protocol (IIOP). You use the rmic compiler to generate the code necessary for connecting your applications via the Internet InterORB Protocol (IIOP) to others written in any CORBA-compliant language. To work with CORBA applications in other languages, IDL can be generated from Java programming language interfaces using the rmic compiler with the -idl option. To generate IIOP stubs and tie classes, use the rmic compiler with the -iiop option. For more information, see the RMI-IIOP documentation.

Scripting for the Java Platform

Java SE includes the JSR 223: Scripting for the Java™ Platform API. This is a framework by which Java Applications can «host» script engines. Java SE includes the Nashorn Engine, which is an implementation of the EMCAScript Edition 5.1 Language Specification. The scripting framework supports third-party script engines through jar «service discovery» mechanism. It is possible to «drop» any JSR-223 compliant script engine in the CLASSPATH and access the same from your Java applications For more information, see the Scripting documentation.

Java Naming and Directory Interface™ (JNDI) API

The Java Naming and Directory Interface™ (JNDI) provides naming and directory functionality to applications written in the Java programming language. It is designed to be independent of any specific naming or directory service implementation. Thus a variety of services—new, emerging, and already deployed ones—can be accessed in a common way. The JNDI architecture consists of a API and an SPI (Service Provider Interface). Java applications use this API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, allowing the Java application using the JNDI API to access their services. For more information, see JNDI documentation.

User Interface Libraries

Input Method Framework

The input method framework enables the collaboration between text editing components and input methods in entering text. Input methods are software components that let the user enter text in ways other than simple typing on a keyboard. They are commonly used to enter Japanese, Chinese, or Korean — languages using thousands of different characters — on keyboards with far fewer keys. However, the framework also supports input methods for other languages and the use of entirely different input mechanisms, such as handwriting or speech recognition. For more information, see the Input Method Framework documentation.

Accessibility

With the Java Accessibility API, developers can easily create Java applications that are accessible to disabled persons. Accessible Java applications are compatible with assistive technologies such as screen readers, speech recognition systems, and refreshable braille displays. For more information, see the Accessibility documentation.

Print Service

The Java™ Print Service API, allows printing on all Java platforms including those requiring a small footprint, such as a Java ME profile. For more information, see Java Print Service documentation.

Sound

The Java platform includes a powerful API for capturing, processing, and playing back audio and MIDI (Musical Instrument Digital Interface) data. This API is supported by an efficient sound engine which guarantees high-quality audio mixing and MIDI synthesis capabilities for the platform. For more information, see Java Sound documentation.

Drag and Drop Data Transfer

Drag and Drop enables data transfer both across Java programming language and native applications, between Java programming language applications, and within a single Java programming language application. For more information, see Drag and Drop Transfer.

Image I/O

The Java Image I/O API provides a pluggable architecture for working with images stored in files and accessed across the network. The API provides a framework for the addition of format-specific plugins. Plug-ins for several common formats are included with Java Image I/O, but third parties can use this API to create their own plugins to handle special formats. For more information, see Image I/O.

Java 2D™ Graphics and Imaging

The Java 2D™ API is a set of classes for advanced 2D graphics and imaging. It encompasses line art, text, and images in a single comprehensive model. The API provides extensive support for image compositing and alpha channel images, a set of classes to provide accurate color space definition and conversion, and a rich set of display-oriented imaging operators. For more information, see the Java 2D documentation.

The Java™ platform’s Abstract Windowing Toolkit (AWT) provides APIs for constructing user interface components such as menus, buttons, text fields, dialog boxes, checkboxes, and for handling user input through those components. In addition, AWT allows for rendering of simple shapes such as ovals and polygons and enables developers to control the user-interface layout and fonts used by their applications. For more information, see the AWT documentation.

Swing

The Swing APIs also provide graphical component (GUI) for use in user interfaces. The Swing APIs are written in the Java programming language without any reliance on code that is specific to the GUI facilities provided by underlying operating system. This allows the Swing GUI components to have a «pluggable» look-and-feel that can be switched while an application is running. For more information, see the Java SE Swing documentation.

JavaFX

Java SE 7 Update 2 and later includes the JavaFX SDK. The JavaFX platform is the evolution of the Java client platform designed to enable application developers to easily create and deploy rich internet applications (RIAs) that behave consistently across multiple platforms. See JavaFX Documentation for more information.

Deployment

Java Deployment

Installation, setup, updating, redistribution and related topics:

  • Installation of the Java Platform on a computer
  • Setting Options in the Java Control Panel
  • Writing applications and applets in the Java Programming language
  • Authoring web pages that invoke applets or download and launch applications
  • Making Java-related files available on web servers
  • Updating the Java Platform on a computer

Tool Specifications

Debugger Architecture

Architecture and specifications for use by debuggers in development environments. For more information, see the Java Platform Debugger Architecture (JPDA) documentation.

VM Tool Interface

The Java Virtual Machine Tool Interface (JVM TI) is a specification for inspecting the state and controlling the execution of applications running in the JVM. The Java Virtual Machine Profiler Interface (JVMPI) has been deprecated. For more information, see the Java Virtual Machine Tool Interface (JVM TI) documentation.

Javadoc Tool

Javadoc is a tool that parses the declarations and documentation comments source files to produce a set of HTML pages describing the program elements. The Doclet API provides a mechanism for clients to inspect the source-level structure of programs and libraries, including Javadoc comments embedded in the source. This API can be used by doclets to generate documentation. For more information, see the Javadoc documentation.

Dynamic Attach

The package com.sun.tools.attach contains an Oracle extension to the Java Platform that allows an application to attach to a running Java virtual machine. Once the attach has been made, a tool agent can be started in the target virtual machine. For more information, see the attach documentation.

JConsole API

The package com.sun.tools.jconsole contains an Oracle extension to the Java Platform that provides a programmatic interface to access JConsole. For more information, see Using JConsole.

JDK Tools & Utilities

Documentation for the tools and utilities included in the JDK. Covers basic tools (javac, java, javadoc, apt, appletviewer, jar, jdb, javah, javap, extcheck), security tools, internationalization tools, RMI tools, IDL and RMI-IIOP tools, deployment tools, Java Plug-in tools, and Java Web Start tools, monitoring and management tools, and troubleshooting tools. For more information, see the JDK Tools and Utilities documentation.

Platforms

Oracle provides implementations of the JDK and Java Runtime Environment for Microsoft Windows, Linux, and the Solaris operating systems. See System Configurations for information about which versions of these platforms are supported.

Other companies may provide implementations of the Java platform for other operating systems such as Macintosh, AIX, etc.

. как установить Java?

Во многих моих тренингах так или иначе используется Java, либо как язык программирования для разработки автотестов, либо как среда для запуска приложений, написанных на Java.

Поэтому я решил описать процедуру установки Java, а также некоторые нюансы настройки Java после установки, которые могут приводить к проблемам при запуске приложений, написанных на Java.

Пять лет назад я уже писал такую инструкцию, но с тех пор накопилось много изменений как в Java, так и в операционных системах, так что пришло время для реновации.

Что устанавливать, JRE или JDK?

Существует две разновидности дистрибутива Java — для простых пользователей и для разработчиков:

  • Java Runtime Environment, или JRE — это виртуальная машина, позволяющая запускать приложения, написанные на языке программирования Java;
  • Java Development Kit, или JDK — это набор инструментов для разработки программ на языке программирования Java (компилятор, архиватор, генератор документации и прочие). JRE разумеется является частью дистрибутива JDK.

Правило очень простое:

  • если вы собираетесь что-нибудь писать на языке программирования Java, значит вам нужен JDK;
  • если вы собираетесь только запускать готовые программы — тогда достаточно JRE.

Какую версию выбрать?

Релизы Java выходят раз в полгода (не считая мелких обновлений). Но не стоит гнаться за новизной. Если вы установите Java последней версии, приготовьтесь к тому, что не все приложения будут хорошо работать с ней. Новые недавно добавленные возможности иногда приводят к проблемам совместимости.

Лучше всего посмотреть статистику и выбрать то, что использует большинство. Давайте посмотрим статистику за 2019 год:

  • Раз: The State of Java Developer Ecosystem in 2019
  • Два: The State of Java in 2019
  • Три: 2020 Java Technology Report

В сентябре 2019 года вышла версия 13, в марте 2020 года выйдет версия 14, но при этом большинство продолжает использовать Java 8!

Я не собираюсь здесь обсуждать причины этого явления, но факт есть факт — это самая распространённая версия по состоянию на конец 2019 года. Поэтому если вы хотите максимальной стабильности и совместимости — в 2020 году берите Java 8.

Второе место по популярности занимает Java 11, это так называемый релиз с долгосрочной поддержкой (Long Term Support, LTS), ориентированный на корпоративных пользователей, для которых стабильность важнее новых фич.

Поддержка Java 8 официально прекращается в декабре 2020 года, к этому времени все корпоративные пользователи будут вынуждены перейти на Java 11. Но вы уже сейчас, не дожидаясь конца 2020 года, можете смело брать эту версию, она обеспечит комфортное соотношение достаточной новизны и не очень высокого риска. А если что-то не будет работать — можно установить рядом Java 8 для использования со старыми приложениями.

Выбирая из 32-битной и 64-битной версий, берите 64-битную, если ваша операционная система это позволяет.

Где взять?

Java это не только язык программирования, но и спецификация, как самого языка, так и среды исполнения программ, написанных на этом языке. Причем это открытая спецификация, поэтому может существовать, и существует, много разных её реализаций, в том числе проприетарных.

Большинство бесплатных реализаций (а может быть даже все) базируются на общем коде, который разрабатывается совместными усилиями вендоров в рамках проекта OpenJDK.

К этому общему коду каждый вендор дописывает свой инсталлятор (со своим логотипчиком), а также может добавлять какие-то дополнительные библиотеки (такие как, например, библиотека для создания графических пользовательких интерфейсов OpenJFX) или утилиты (например, средства мониторинга).

Лично я отдаю предпочтение сборке Azul Zulu, но вы можете выбрать какую-нибудь другую.

Как установить?

На примере сборки Azul Zulu.

В операционной системе Windows:

  1. выберите сборку и версию, как описано в предыдущих разделах;
  2. загрузите инсталлятор (файл с расширением .msi );
  3. запустите инсталлятор и следуйте инструкциям на экране.

В операционной системе Linux:

  1. выберите сборку и версию, как описано в предыдущих разделах;
  2. загрузите пакет (файл с расширением .deb или .rpm );
  3. в консоли выполните команду
    sudo apt install <путь к загруженному deb-файлу>
    либо
    sudo rpm -i <путь к загруженному rpm-файлу>

В операционной системе MacOS:

  1. выберите сборку и версию, как описано в предыдущих разделах;
  2. загрузите образ диска (файл с расширением .dmg );
  3. откройте загруженный образ диска;
  4. запустите находящийся внутри него инсталлятор и следуйте инструкциям на экране.

Как проверить правильность установки?

В операционной системе Windows нужно запустить консоль ( cmd ) и выполнить команду where java , которая должна показать правильный путь до исполняемого файла java.exe , а также после этого выполнить команду java -version для проверки того, что это именно та версия, которую вы устанавливали:

В операционной системе Linux и MacOS нужно запустить консоль и выполнить команду which java , которая должна показать правильный путь до исполняемого файла java (скорее всего это будет /usr/bin/java ), а также после этого выполнить команду java -version для проверки того, что это именно та версия, которую вы устанавливали:

Что ещё надо сделать?

Инсталлятор Java выполняет минимальную необходимую настройку окружения, в том числе он добавляет в переменную среды PATH путь к директории, которая содержит исполняемые файлы Java (в операционной системе Windows), либо создаёт в стандартной директории для исполняемых файлов символические ссылки на установленные исполняемые файлы Java (в других операционных системах).

Но некоторые программы вместо этого используют переменную среды JAVA_HOME , которая должна указывать на директорию, в которую установлена Java. Поэтому на всякий случай можно сразу установить эту переменную.

Для этого надо научиться определять, куда установлена Java.

В операционной системе Windows путь к директории установки можно увидеть, выполнив команду where java в консоли. Например, если вы установили сборку Zulu JDK версии 8, эта команда вернёт значение C:\Program Files\Zulu\zulu-8\bin\java.exe , а в переменную JAVA_HOME нужно установить значение C:\Program Files\Zulu\zulu-8 .

В операционной системе Linux нужно посмотреть, куда указывает символическая ссылка java , это можно сделать командой readlink -f $(which java) . Например, если вы установили сборку Zulu JDK версии 8, эта команда вернёт значение /usr/lib/jvm/zulu-8-amd64/jre/bin/java , а в переменную JAVA_HOME нужно установить значение /usr/lib/jvm/zulu-8-amd64/jre . Чтобы эта переменная среды устанавливалась автоматически при входе в систему, можно в файл

/.profile добавить строчку export JAVA_HOME=$(readlink -f $(which java) | sed «s:/bin/java::») .

В операционной системе MacOS есть специальная команда /usr/libexec/java_home , которая возвращает нужный путь. Например, если вы установили сборку Zulu версии 8, эта команда вернёт значение /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home , именно это значение и нужно установить в переменную JAVA_HOME . Чтобы эта переменная среды устанавливалась автоматически при входе в систему, можно в файл

/.profile добавить строчку export JAVA_HOME=$(/usr/libexec/java_home) .

А если вы собираетесь писать код на языке программирования Java, информация о расположении Java пригодится при настройке среды разработки.

Алексей Баранцев

Автор: Алексей Баранцев

Если вам понравилась эта статья, вы можете поделиться ею в социальных сетях (кнопочки ниже), а потом вернуться на главную страницу блога и почитать другие мои статьи.
Ну а если вы не согласны с чем-то или хотите что-нибудь дополнить – оставьте комментарий ниже, может быть это послужит поводом для написания новой интересной статьи.

What is Java Runtime Environment

Use My Notes

In this tutorial, we will learn about one of the core components of Java i.e the what is Java Runtime Environment. We will cover its basic structure and understand why it is needed in Java. This tutorial will also cover the installation of JRE into your local computer.

What is the Java Runtime Environment (JRE)?

Any software that is executed needs an environment in which it can rest and operate. The primary environment in a computer is its operating system (OS). All the software generally runs on the OS. It is not efficient to always run everything on the OS directly.

Specifically for Java programs, there is a special environment that can run Java programs virtually on an OS, it is called the Java Runtime Environment (JRE). The Java Virtual Machine (JVM) which is the core part of Java responsible for executing Java programs also sits on the JRE. We can say JVM is a subset of JRE.

The JRE provides a virtual platform on which the JVM and other Java libraries rest on. These components of JRE are virtually isolated and used for executing Java programs. A system that doesn’t have JRE cannot run Java programs. We have to install JVM for executing Java programs and applications. Also, know that the JDK or Java Development Kit already has JRE within it. A system that has JDK installed doesn’t have to install JRE separately.

What does JRE do?

Executing a Java program is easy. But the underlying architecture of the JRE defines what is needed for it to be executed. The JRE contains all the libraries and core classes that are needed to execute a Java program. Whenever we execute a Java program, the JRE combines the needed classes and other libraries with the JVM that is required for that program. The JVM then loads these classes and libraries and creates a virtual environment to execute the code.

Why use JRE when we have JDK?

JDK is a development kit that has all the tools and utilities that can be used to create Java programs and applications. These tools are basically for developers for developing and debugging purposes. If you are a developer then you need JDK to develop Java applications.

But if you are a user who just needs to use/execute Java applications that are already built by a developer, then you just have to install JRE on your computer which only includes components that are required to execute Java applications. This will prevent you from installing unnecessary tools that are developer-specific and not required.

How to install JRE?

The installation of JRE is similar to installing JDK. In this tutorial, we will be covering the Windows operating system.

If you are interested to learn how to install java JRE so kindly visit it.

Что такое среда выполнения для Java?

Среда выполнения для Java (JRE) – это программное обеспечение, которое требуется для корректной работы программ Java. Java – это язык программирования, на котором написаны многие современные мобильные и интернет-приложения. JRE – это базовая технология, которая взаимодействует с Java-программой и операционной системой. Она действует как переводчик и посредник, предоставляя все ресурсы, чтобы после написания программного обеспечения на Java оно работало на любой операционной системе без дополнительных модификаций.

Почему JRE является столь важной?

Программе необходима среда выполнения, которая обеспечивает доступ к памяти и другим системным ресурсам, таким как программные файлы и зависимости. В прошлом большинство программ использовали непосредственно операционную систему в качестве среды выполнения. Однако это означало, что разработчикам приходилось писать отдельный код для каждой операционной системы, на которой они хотели, чтобы работали их приложения. Технология среды выполнения для Java (JRE) была создана как решение этой проблемы.

JRE – это один из трех компонентов платформы Java, которые необходимы для успешного выполнения любой программы на Java. Пакет средств разработки Java (JDK) и виртуальная машина Java (JVM) – это два других компонента.

Пакет средств разработки Java

JDK – это набор программных инструментов, которые можно использовать для разработки Java-приложений. Вы можете использовать JDK в своей среде разработки, скачав и установив его. Выберите версию программного обеспечения JDK, соответствующую версии Java, которую хотите использовать. Например, Java Standard Edition, или Java SE, требует Java SE JDK.

Виртуальная машина Java

JVM – это программное обеспечение, которое выполняет программу Java построчно. Разработчики настраивают параметры JVM для управления ресурсами программы при запуске Java-приложения. Например, вы можете изменить настройку памяти JVM и проверить, сколько внутренней памяти используют ваши Java-приложения во время выполнения.

Роль JRE в языке программирования Java

JRE объединяет код Java, который вы создаете с помощью JDK, с дополнительным встроенным кодом, называемым библиотеками. Затем он создает инстанс JVM или локальную копию, которая в конечном итоге запускает Java-программы. JVM доступны для множества операционных систем, а JRE генерирует единую копию вашего Java-кода, который работает на всех типах JVM. Таким образом, JRE обеспечивает платформенную независимость Java-приложений. Вы можете написать их один раз и запустить в любом месте.

Разница между JRE, JVM и JDK

JDK – это программный слой над JRE, который содержит компилятор, отладчик и другие инструменты, обычно встречающиеся в любой среде разработки программного обеспечения. В JDK вы пишете код с использованием синтаксиса, подобного английскому языку. JDK компилирует его и передает байт-код в JRE. В отличие от этого, JRE содержит библиотеки классов, вспомогательные файлы и JVM. Здесь используются эти программные компоненты для запуска байт-кода на любом устройстве.

Как работает JRE?

Среда выполнения Java (JRE) работает поверх операционной системы, предоставляя дополнительные ресурсы, специфичные для Java. Пакет средств разработки Java (JDK) и JRE взаимодействуют для создания устойчивой среды выполнения, которая запускает программные файлы Java на любой машине. JRE использует для работы три основных компонента.

ClassLoader

Библиотеки классов Java содержат коллекции заранее написанного кода, который можно вызывать по мере необходимости. Они упрощают работу Java-разработчиков, предоставляя встроенные методы для таких распространенных и нетривиальных задач, как прием входных данных от пользователей, отображение выходных данных для пользователей и многое другое. Все программы на Java ссылаются на несколько библиотек классов. Java ClassLoader динамически загружает все необходимые файлы классов в виртуальную машину Java (JVM) по требованию.

Верификатор байткода

В JDK есть компилятор, который преобразует написанный вами англоязычный код в версию на машинном языке, называемую байткодом Java. Верификатор байткода в JRE проверяет формат и точность кода Java перед его загрузкой в JVM. Например, если код нарушает целостность системы или права доступа, JRE не загрузит файл класса.

Переводчик

После успешной загрузки байткода интерпретатор Java создает инстанс JVM, который запускает программу Java на базовой машине.

Из каких компонентов состоит JRE?

Помимо основных компонентов, среда выполнения для Java (JRE) содержит несколько других программных компонентов, которые помогают более эффективно выполнять Java-программы. Далее приведены некоторые примеры.

Инструменты разработки

JRE содержит средства разработки, такие как наборы инструментов пользовательского интерфейса, которые можно использовать для улучшения качества ваших приложений. Далее приведены некоторые примеры.

Java 2D

Java 2D – это интерфейс прикладных задач (API), который можно использовать для рисования двумерной графики и создания прекрасных пользовательских интерфейсов, игр, анимации и специальных эффектов на языке Java.

Swing

Swing – это легкий графический интерфейс пользователя (GUI), который обеспечивает гибкую, удобную для пользователя настройку.

Abstract Window Toolkit

Abstract Window Toolkit (AWT) – это графический интерфейс, который можно использовать для создания объектов пользовательского интерфейса, таких как кнопки, окна и полосы прокрутки.

Решения по развертыванию

JRE включает технологии, которые упрощают процесс выпуска изменений программного обеспечения для пользователей приложений. Эти технологии также обеспечивают расширенную поддержку обновлений в приложении. Технологии развертывания, такие как Java Web Start и плагин Java, включены как часть установки JRE. Эти технологии упрощают активацию приложений, а также обеспечивают расширенную поддержку будущих обновлений JRE. Далее приведены некоторые примеры.

Java Web Start

С помощью Java Web Start вы можете запускать полнофункциональные приложения одним щелчком мыши из веб-браузера.

Плагин Java

Плагин Java устанавливает соединение между популярными браузерами и платформой Java, что позволяет запускать апплеты в браузерах для настольных компьютеров.

Библиотеки языков и утилит

Коллекция файлов классов Java называется пакетом Java. JRE включает несколько пакетов Java, которые поддерживают версионность, управление и мониторинг. В качестве примера можно привести следующие пакеты:

Система коллекций

Система коллекций представляет собой единую архитектуру, включающую интерфейсы для улучшения хранения и обработки данных приложений.

API предпочтений

API предпочтений позволяет нескольким пользователям на одной машине определять собственную группу предпочтений приложений.

Ведение журналов

С помощью пакетов журналов создаются отчеты журналов для устранения неисправностей, таких как сбои в системе безопасности, проблемы с производительностью и ошибки конфигурации.

Архив Java

Архив Java (JAR) – это независимый от платформы формат файлов, позволяющий объединять несколько файлов для уменьшения размера файлов приложений и значительного повышения скорости загрузки.

Интеграционные библиотеки

JRE включает несколько интеграционных библиотек, которые помогают разработчикам создавать удобные соединения данных между сервисами и приложениями. Ниже приведены некоторые примеры библиотек.

Java IDL

Язык Java Interface Definition Language (IDL), который основан на архитектуре Common Object Request Broker Architecture (CORBA), поддерживает распределенные объекты данных, то есть объекты, которые взаимодействуют на разных платформах по сети. Например, Java IDL позволяет объектам, написанным на Java, взаимодействовать с объектами, написанными на другом языке, таком как C, C++ или COBOL.

Подключение к базам данных Java

Разработчики используют API Java Database Connectivity (JDBC) для написания приложений, которые могут обращаться к удаленным базам данных, электронным таблицам и файлам.

Java Naming and Directory Interface

Java Naming and Directory Interface (JNDI) – это сервис каталогов, позволяющий клиентам создавать переносимые приложения, которые получают информацию из внешних баз данных, используя правила именования.

Что такое AWS SDK для Java?

Пакет средств разработки ПО (SDK) AWS для Java упрощает использование сервисов AWS, предоставляя упорядоченный набор библиотек, с которыми знакомы разработчики Java. AWS SDK for Java также поддерживает более высокий уровень абстракций для упрощения разработки. Доступны библиотеки Java с открытым исходным кодом, ориентированные на AWS, а также примеры кода и справочное руководство по API Java.

Примеры кода AWS SDK для Java 2.0 на GitHub содержат примеры на языке Java и реальные примеры работы с сервисами AWS, которые ускорят разработку собственных приложений. Кроме того, справочник AWS SDK по Java API описывает работу API в новейшей версии AWS SDK для Java. Кроме того, приводятся образцы запросов, ответов и список ошибок для поддерживаемых сетевых протоколов.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *