What is the difference between ManagedExecutorService and ExecutorService in java

Viewed 5706

I have a requirement of submitting task to executor service in my wildfly java ee application.

The current code is as below,

ExecutorService jobExecutorService = Executors.newSingleThreadExecutor(); jobExecutorService.submit(new Task(request));

On each request, the same piece of code will run and submit the task for single-threaded executor.

But I am not sure whether the newly constructed thread is managed or is it a correct way of submitting tasks in my java ee application for any async flow.

If I need to start a thread which should be managed by the container, do I need to use ManagedExecutorService or is there any other implementation.

Need some knowledge on this.

2 Answers

To answer the question out of the title:

ManagedExecutorService is part of the Java EE specification while ExecutorService is part of the Java SE specification.

The main difference between these two interfaces is that the ManagedExecutorService is just a

manageable version of a ExecutorService.

Since you should not spawn any unmanaged Thread in an Java EE environment, you should only use the managed stuff there, while the unmanaged is perfectly fine for Java SE applications.

The proper way to get a ManagedExecutorService in a Java EE application is to inject the ManagedExecutorService with the @Resource annotation

@Resource
ManagedExecutorService managedExecutorService;

ExecutorService does n't need any web container, where as ManagedExecutorService is used in the context of application deployed to a webserver, where threadpools are created and their life cycles are maintained by the container.

Related