java форум

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » java форум » Main форум » Java Concurrency API


Java Concurrency API

Сообщений 1 страница 12 из 12

1

Я пока не знаю, что это такое, но горю желанием изучить.
UPD: в общем, это всё про веб-приложения. А если надо в сервисе/демоне/службе одновременное/параллельное, то нужно что-то другое.

2018-08-30, MaxRokatansky, Java EE Concurrency API
https://habr.com/ru/companies/otus/articles/421809/

Интересуют вопросы:
1) в какой версии Java это появилось;
2) зачем оно нужно в принципе;
3) какими стандартами это описывается;
4) литература и статьи в интернете;
5) примеры какие-нибудь.

-------------------------------------------------------------

API ~> прикладной программный интерфейс (ППИ).

1) «Выход седьмой версии JavaEE сделал возможным запуск параллельных задач в Enterprise-контейнерах, предоставляя разработчику удобные средства и утилиты для работы с многозадачностью.»
Тут надо разузнать после (потом), какая это была дата, какая это версия JDK, тоже седьмая?

«JavaTM Platform, Enterprise Edition 1.4 or later.»
Ну да, из того, что седьмая очевидно вытекает 1.4...
1.4 это в драфте написано, а читать надо релиз спецификации:
https://jcp.org/aboutJava/communityproc … index.html

А сейчас этот код как поставляется - в составе JDK, или отдельной библиотекой?

jakarta.enterprise.concurrent это новое название для javax.enterprise.concurrent
Это изменение произошло с выходом Jakarta EE 9 (был переименован в  в рамках перехода от Java EE к Jakarta EE)

2)
E: «There is commonly a need to perform application-level work concurrently or periodically using different threads of execution.»
Р: «Обычно возникает необходимость выполнять работу на уровне приложения одновременно или периодически, используя разные потоки выполнения.»
А почему она возникает? Только ли для того, чтобы использовать аппаратуру эффективнее, или зачем вообще? В web и так много запросов от разных пользователей, контейнер и так их разбросает по разным потокам и процессоры и так будут все использоваться.

«Когда несколько потоков операционной системы пытаются одновременно получить доступ к одному и тому же ресурсу, это может привести к состояниям гонки или другим проблемам.»
И чего, значит ли это что реализация этого ППИ потокобезопасная?

«web component container do not allow using common Java SE concurrency APIs such as java.util.concurrent.ThreadPoolExecutor, java.lang.Thread,java.util.concurrent.ScheduledThreadPoolExecutor or java.util.Timer directly.» (ц)
Не ясно:
- где (в каком документе) сказано, что web-контейнеры так не могут ("do not allow");
- почему они не могут.

3)
JSR 236
«provides a simple, standardized API for using concurrency from application components without compromising container integrity while still preserving the Java EE platform's fundamental benefits»
Точно ли это именно для Java EE или для Jakarta тоже сойдёт?

duck.ai написал(а):

с переходом от Java EE к Jakarta EE, многие из этих концепций и API были перенесены и адаптированы для Jakarta EE

«предоставляет простой, стандартизированный прикладной программный интерфейс (ППИ) для компонентов приложения, позволяющий использовать многопроцессорность, многоядерность и/или аппаратные потоки, сохраняющий целостность контейнера, при этом сохраняя основные преимущества платформы»
А при чём тут контейнер вообще, просто в приложении можно это использовать?

0

2

Почему и/или когда на уровне web-приложения (веб-сайта, сайта) возникает необходимость выполнять работу одновременно или периодически?

E: «For example, a Servlet or JSP may need to pull data from several back end data sources or services before rendering HTML.»
Р: «Например, сервлету или web-странице (JSP) может потребоваться извлечь данные из нескольких внутренних источников данных или служб перед отображением HTML.»

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

Пример:
Пришел поисковый запрос от пользователя, искать в файлах будем по запросу, файлов много.
(Можно было бы заранее сделать индекс, зачем искать в момент запроса?)
Ну, тогда, будем формировать фрагменты ответов для каждого из файлов, подсвечивая слова в поисковом запросе.
Каждый фрагмент одновременно и параллельно.

0

3

«Java APIs for concurrent programming, including JSR-166.»
Надо потом почитать будет, что это такое (так сказать, какой у них там полный список всех разных ППИ (API)).

«common Java SE concurrency APIs such as»
java.lang.Thread
java.util.concurrent.ExecutorService (интерфейс)
java.util.concurrent.ThreadPoolExecutor
java.util.concurrent.ScheduledThreadPoolExecutor
java.util.Timer
«should never be used within managed environments, as it creates threads outside the purview of the container. Further, there is no clean way of subclassing java.util.Timer to avoid thread creation, as all constructors create and start a thread.»
javax.management.timer.Timer
«is tightly coupled with the JMX framework and does not provide a sufficiently user-friendly or independent API.»

java.util.concurrency
«Java SE Concurrency Utilities»
«package with Java SE concurrency utilities (JSR-166)»

JCA WorkManager API
«is only appropriate for use within Resource Adapters»

0

4

Не получается скачать документы из-за санкций:

Oracle написал(а):

In compliance with U.S. and applicable Export laws we are unable to process your request to https://edelivery.oracle.com/otn-pub/jc … .0-fr.pdf.  Please contact RPLS-Ops_ww@oracle.com if you believe you are receiving this notice in error.

Oracle написал(а):

In compliance with U.S. and applicable Export laws we are unable to process your request to https://edelivery.oracle.com/otn-pub/jc … vadoc.jar.  Please contact RPLS-Ops_ww@oracle.com if you believe you are receiving this notice in error.

Надо попробовать в Jakarta EE посмотреть, вдруг есть там?

https://jakarta.ee/specifications/concurrency/
https://jakarta.ee/specifications/concurrency/3.2/
Target Environments
Java SE 21 and Java SE 25

https://projects.eclipse.org/projects/ee4j.cu

https://jakarta.ee/specifications/concurrency/2.0/
2020-10-08, Release (for Jakarta EE 9)
https://jakarta.ee/specifications/concu … y-spec-2.0
https://jakarta.ee/specifications/concu … ec-2.0.pdf

0

5

https://forumupload.ru/uploads/001c/76/d2/3/t475143.jpg
На этой картинке мы видим, что можно в разных нитях операционной системы вызывать сервлеты (и веб-страницы) как будто-бы они работают в той же нити, в которой был оригинальный запрос от клиента. И это обязательно надо опробовать, потом, когда-нибудь.

0

6

Tasks are units of work that represent a computation or some business logic.
Tasks are concrete implementations of the Java SE java.util.concurrent.Callable and java.lang.Runnable interfaces (see the Javadoc for java.util.concurrent.ExecutorService).
Task classes can optionally implement the jakarta.enterprise.concurrent.ManagedTask interface to provide execution properties and to register a jakarta.enterprise.concurrent.ManagedTaskListener instance to receive lifecycle events notifications.

java.util.concurrent.Callable
    call()

java.lang.Runnable
    run()

jakarta.enterprise.concurrent.ManagedTaskListener
    taskAborted()
    taskSubmitted()
    taskStarting()

jakarta.enterprise.concurrent.Trigger
    getNextRunTime()
    skipRun()

These methods can be made contextual through the ContextService, which can make any Java object contextual.
ContextService – The interface for creating contextual objects.

A contextual object is any Java object instance that has a particular application component’s thread context associated with it.
When a task instance is submitted to a managed instance of an ExecutorService, the task becomes a contextual task.
When the contextual task runs, the task behaves as if it were still running in the container it was submitted with.

Contextual Objects and Tasks referred here is not the same as the Context object as defined in the Jakarta Contexts and Dependency Injection specification.

ManagedExecutorService –The interface for submitting asynchronous tasks from a container.
ManagedScheduledExecutorService – The interface for scheduling tasks to run after a given delay or execute periodically.

ManagedThreadFactory – The interface for creating managed threads
А зачем нужны нити, если уже есть возможность запускать задачи через сервис ManagedExecutorService?
Не надо запускать, это просто имя, которое мы указываем в настройках пула задач
«ThreadFactory: A reference to a ManagedThreadFactory instance.
The managed ThreadFactory instance can create threads with different attributes (such as priority)»

jakarta.enterprise.concurrent.ManagedExecutorService
«is an interface that extends the java.util.concurrent.ExecutorService interface»

Instances for these objects are retrieved using the Java Naming and Directory Interface (JNDI) Naming Context (EE.5)
or through injection of resource environment references (EE.5.8.1.1).
(надо бы примерчик, в будущем/пото́м, как же в коде web-приложения получить объект типа ManagedExecutorService с интерфейсом ExecutorService, и как через него создать задачу)

Task instances are submitted to a ManagedExecutorService instance using any of the defined submit(), execute(), invokeAll(), or invokeAny() methods. Task instances will run as an extension of the Jakarta EE container instance that submitted the task and may interact with Jakarta EE resources

0

7

This specification addresses the need for Jakarta EE applications to run application business logic asynchronously using a jakarta.enterprise.concurrent.ManagedExecutorService or java.util.concurrent.ExecutorService with a jakarta.enterprise.concurrent.ManagedThreadFactory.

A ManagedExecutorService instance is intended to be used by multiple components and applications. When the executor runs a task, the context of the thread is changed to match the component instance that submitted the task. The context is then restored when the task is complete.

The types of contexts to be propagated by this default ManagedScheduledExecutorService from a contextualizing application component must include naming context, class loader, and security information.

The handle to the task (the Future) is cached so that the client can query the results of the report.
The Future will contain the results once the task has completed.

Код:
    // Get the name of the report to run from the input params...
    // Assemble the header for the response.
    // Create a task instance
    ReporterTask reporterTask = new ReporterTask(reportName);

    // Submit the task to the ManagedExecutorService
    Future reportFuture = mes.submit(reporterTask);

0

8

resource environment references are declared in the deployment descriptor

ManagedExecutorService references should be bound in the java:comp/env/concurrent subcontext

The Jakarta EE Product Provider must provide a preconfigured, default ManagedExecutorService for use by application components under the JNDI name java:comp/DefaultManagedExecutorService.

configure a ManagedExecutorService and the possible options that such a service could provide.

Core Size: The number of threads to keep in the pool, even if they are idle.
Maximum Size: The maximum number of threads to allow in the pool (could be unbounded).
Keep Alive: The time to allow threads to remain idle when the number of threads is greater than the core size.
Work Queue Capacity: The number of tasks that can be stored in the input bounded buffer (could be unbounded).
Hung Task Threshold: The amount of time in milliseconds that a task can execute before it is considered hung.

0

9

У меня ещё такое наблюдение есть:
Вместо этого менеджера тасков можно же переложить всё на клиента.
Клиент будет динамически (через JavaScript) запрашивать разные фрагменты ответа,
запрашивать их с сервера через что-нибудь (например через REST API),
и тогда получается, что на сервере всё будет однопоточное,
а управлением потоками будет заниматься клиент по мере прорисовки/прокрутки.

Одно останавливает - JavaScript может быть отключен.
С другой стороны, зачем всякое легаси поддерживать?
Таким образом, необходимость в одновременной/параллельной обработке в web-приложении (в рамках одного запроса) мне пока всё равно не очевидна.

0

10

https://jakarta.ee/specifications/concu … extservice

jakarta.enterprise.concurrent.ContextService
«allows applications to create contextual objects without using a managed executor»

Instances for these objects are retrieved using the Java Naming and Directory Interface (JNDI) Naming Context (EE.5) or through injection of resource environment references (EE.5.8.1.1).

all ContextService references should be declared in the java:comp/env/concurrent subcontext.

The Jakarta EE Product Provider must provide a preconfigured, default ContextService for use by application components under the JNDI name java:comp/DefaultContextService.

whenever a method on the contextual object is invoked, the method executes with the thread context of the associated application component instance.

The ContextService uses the dynamic proxy capabilities found in the java.lang.reflect package to associate the application component container context with an object instance.
Contextual object proxy instances are created with a ContextService instance using the createContextualProxy() method.

task logs the request in a database, which requires the local namespace in order to locate the correct Datasource.

0

11

Вопрос - как запустить фоновую задачу при старте веб-приложения?

Возражение - зачем вообще всё пихать в один процесс? Упадёт, например, индексирование файлов, и это приведёт к перезапуску веб-приложения и, возможно, прервутся сессии пользователей (если они хранятся в памяти).

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

0

12

«доступ к объектам с интерфейсами ManagedExecutorService и ContextService осуществляется через внедрение ресурса, используя аннотацию @Resource»

пример?

Код:
@Resource
ManagedThreadFactory factory;

@Resource
ContextService service;

И как вообще аннотации работают надо почитать. Понятно, что всё это SpringBoot, Dependency Injection, IoC, и т.д., просто записанных подробностей у меня нет.

0


Вы здесь » java форум » Main форум » Java Concurrency API