Giriş
Açıklaması şöyle
One of the most commonly used services in the Jakarta Concurrency API is the ManagedExecutorService. It is used to create a thread pool in the Jakarta EE environment to spawn threads in a more manageable way. Although it is pretty much the same as ExecutorService, we employ it in the Java SE environment.
To configure the thread pool, we had a vendor-specific setting. Now it can be defined with just annotation. This is a more standard way of configuring the thread pool.
Örnek
Şöyle yaparız
@Path("concurrency")@RequestScoped public class GenericResource { @Context private UriInfo context; @Resource private ManagedExecutorService managedExecutor; @GET @Path("simplejob") @Produces(MediaType.TEXT_PLAIN) public String getText() { manageExecutor.submit(() -> { System.out.println("Job running..."); }); return "Job Sumitted"; } }
Örnek
Şöyle yaparız
import static jakarta.enterprise.concurrent.ContextServiceDefinition.APPLICATION;import static jakarta.enterprise.concurrent.ContextServiceDefinition.SECURITY;import jakarta.annotation.Resource;import jakarta.ejb.Asynchronous;import jakarta.enterprise.concurrent.ContextServiceDefinition;import jakarta.enterprise.concurrent.ManagedExecutorDefinition;import jakarta.enterprise.concurrent.ManagedExecutorService;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Named;import java.time.Duration;import java.time.LocalDate;import java.util.concurrent.CompletableFuture;@Named@ApplicationScoped@ManagedExecutorDefinition(name = "java:module/concurrent/MyExecutor",context = "java:module/concurrent/MyExecutorContext",hungTaskThreshold = 120000,maxAsync = 5)@ContextServiceDefinition(name = "java:module/concurrent/MyExecutorContext",propagated = {SECURITY, APPLICATION})public class WorkService {@Resource(name = "java:app/concurrent/MyExecutorService")private ManagedExecutorService executor;@Asynchronouspublic CompletableFuture<Long> hoursWorked(LocalDate from, LocalDate to) {return CompletableFuture.supplyAsync(() -> heavyAPICall(from, to), executor);}private static long heavyAPICall(LocalDate from, LocalDate to) {return Duration.between(from, to).toMillis();}}