Using CDI With Java EE Concurrency Utilities
If you aren't familiar with Java EE Concurrency Utilities, it's time to take a look at what the specification has to offer. We'll examine how it works with CDI here.
Join the DZone community and get the full member experience.Join For Free
This blog post explores the usage of CDI along with Java EE Concurrency Utilities – specifically using CDI beans as managed tasks. Here is the sample application on GitHub.
Let's Begin With a Quick Overview
Java EE Concurrency Utilities provides APIs and constructs to manage concurrency within Java EE applications. Many of the Java EE components have specific concurrency semantics e.g. EJBs, JAX-RS resources, WebSocket endpoints, etc. Writing components with custom concurrency properties was traditionally difficult, since starting unmanaged threads in a Java EE container was forbidden, i.e. one was not able to leverage Java SE concurrency libraries. With Concurrency Utilities, Java EE applications have access to managed versions of the Java SE counterparts, namely,
...and a bunch of other APIs as well, but the above ones are the Java EE equivalent of the Java SE concurrency APIs.
Tasks as CDI Beans
ManagedScheduledExecutorService can accept tasks to execute (in a container-managed thread pool) in the form of
Callable instances. The good thing is that these tasks can be CDI beans as well. Points worth noting are:
- These CDI beans can be injected into other components as well as inject other beans.
- The scope of the CDI beans, which can be used as tasks as restricted to
@Dependent(for details, read section
18.104.22.168of the specification).
Here Is a Summary of...
- Tasks are
POSTEDvia a REST interface and the client gets back a
HTTP 202 (Accepted)in response along with a task id
BackgroundTask(CDI bean) is executed in a background thread by the
ManagedExecutorService– it is injected (
@Inject) and a different instance is created on every invocation since the CDI bean is marked
@Dependentand the JAX-RS resource is created on each request by the client
- The status is store in a
TaskStore) – this is injected in the
- Status of each task (in progress, failed, completed) can be tracked via a REST interface by querying against a
- One can also get the status of all tasks
If you want to read more, take a look at this Concurrency Utilities specification.
Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.