Controlling number of Threads for ManagedExecutorServices / Java EE 7 - java

In Java SE one can use constructs like
ExecutorService es1 = Executors.newSingleThreadExecutor();
ExecutorService es2 = Executors.newFixedThreadPool(10);
to control the number of threads available to the executor service. In Java EE 7 it's possible to inject executor services:
#Resource
private ManagedExecutorService mes;
But how can I control the number of threads available to the managed executor service ? For example, in the application I'm writing, there is an executor service that has to be executed in a single thread. So I can't just let the platform choose its preferred number of threads.

Actually, this setting should be set in the server settings, through admin console (in GlassFish for example), or during the creation of the service:
asadmin create-managed-executor-service --corepoolsize=10 --maximumpoolsize=20 concurrent/mes
See Create ManagedExecutorService, ManagedScheduledExecutorService, ManagedThreadFactory, ContextService in GlassFish 4.

Related

Executor service shutdown is not supported

I am using the executor service provided by IBM Websphere 8.5.5
ExecutorService es = (ExecutorService ) new InitialContext().lookup("wm/default")
when I call es.shutdown()method, I get the error:
java.lang.IllegalStateException: ASYN0093E: The operation shutdown is not supported.
Why Websphere does not support the shutdown method? Should not I call that method?
WebSphere Application Server rejects the shutdown method in order to comply with the following requirement of the Concurrency Utilities for Java EE Specification, Section 3.1.6: Lifecycle , which states:
The lifecycle of ManagedExecutorService instances are centrally managed by the application server and cannot be changed by an application.
And more explicitly, Section 3.1.6.1 Java EE Product Provider Requirements , which explicitly states:
The lifecycle of a ManagedExecutorService is managed by an application server. All lifecycle operations on the ManagedExecutorService interface will throw a java.lang.IllegalStateException exception. This includes the following methods that are defined in the java.util.concurrent.ExecutorService interface: awaitTermination(), isShutdown(), isTerminated(), shutdown(), and shutdownNow().
It seems likely this requirement exists to prevent applications from interfering with each other when both use the same executor.

What is the difference between ManagedExecutorService and ExecutorService in java

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.
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.

EJB #Schedule is synchronous or asynchronous?

As #Balus has explained in Spawning threads in a JSF managed bean for scheduled tasks using a timer
EJB available? Use #Schedule
If you target Java EE 6 or newer (e.g. JBoss AS, GlassFish, TomEE, etc and thus not a barebones JSP/Servlet container such as Tomcat), then use a #Singleton EJB with a #Schedule method instead. This way the container will worry itself about pooling and destroying threads via ScheduledExecutorService.
So i am curious to know by using #Schedule, the background process will run asynchronously by container managed threads (magically) or it is like a java.util.timer which creates single thread and all process run within this threads??
if #Schedule creates only single thread just to manage the scheduler then would it be safe to use further ScheduledExecutorService within #Schedule? and this ScheduledExecutorService contains further runnable tasks based on multiple threads.
I have a long running process including file manipulation, data processing and email generating, but really should i rely only on this single #Schedule annotation without using any executorservices/creating further threadpool?? BTW i am using Glassfish.

How to reliably kill #Scheduled threads across servers?

I'm building a plugin that is implemented as a Spring MVC application. This plugin is deployed on 3 - 6 tomcat servers via a gui on one of the servers. Each of the instances of the plugin has an #Scheduled method to collect information on the server and store it in a central database.
My issue is that the gui interface for uninstalling the plugin leaves some of the #Scheduled threads running.
For example, I have an environment that has servers 1 - 3. I install and enable the plugin via the gui on server 1. There are now 3 instances of the application running #Scheduled threads on servers 1 - 3. If I go back to server 1 and uninstall the plugin, the thread is reliably killed on server 1 but not servers 2 or 3.
I've implemented the following but the behavior persists:
#Component
public class ContextClosedListener implements ApplicationListener<ContextClosedEvent> {
#Autowired
ThreadPoolTaskExecutor executor;
#Autowired
ThreadPoolTaskScheduler scheduler;
public void onApplicationEvent(ContextClosedEvent event) {
scheduler.shutdown();
executor.shutdown();
}
}
Additionally, I've thought of implementing this as a context listener rather than an #Scheduled method but I'd rather stick to Spring for maintenance and extensibility reasons.
How can I reliably kill threads in an environment like this?
A couple thoughts I have. ThreadPoolTaskExecutor has a method setThreadNamePrefix, which allows you to set the prefix of the thread. You could set the prefix to something unique, then find and kill those threads at runtime. You can also set the thread group using the setThreadGroup method on the same object, then just stop the threads in the threadgroup.
The better, and safer, solution would be to create a break-out method in your scheduled jobs. This is the prefered method to stopping a Thread instead of the old "shot it in the head" method of calling Thread.stop(). You could get reference to those Runnables either by setting a common prefix or by using the thread group as described above.
The next question is: how do you stop the threads easily? For that, it would depend on how your appliation is implemented. Since I deal mainly with Spring MVC apps, my first solution would be to write a Controller to handle admin tasks. If this was JBoss, or some other large app server that had JMX (Tomcat can be configured to provide JMX I believe, but I don't think its configured out of the box that way), I might write a JMX-enabled bean to allow me to stop the threads via the app servers console. Basically, give your self a method to trigger the stopping of the threads.

Custom thread in JAX-WS web method

I have a problem with web service via JAX-WS. If I start thread in web method, it will be ended while connection with client ended.
Example:
#WebMethod(operationName="test")
public boolean test()
{
Thread th = new MyThread();
th.start();
// Thread is running
...
return true;
// Now thread th ends;
}
Is there any solution to keep thread th running?
The problem is that you are trying to start a Thread on a Java EE app server. Manual threading is in violation of the Java EE specs, which is why you are running into problems. on some app servers you can't even start a separate thread at all. From the spec:
The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.These functions are reserved for the EJB container. Allowing the enterprise bean to manage threads would decrease the container’s ability to properly manage the runtime environment.
If you need to do the work on a separate thread, you need to use the facilities provided by the app server for asynchronous work. some options are queueing the data to a JMS queue for processing by an MDB or possibly using an asynchronous ejb request (think that's in Java EE 6).
If you just want to be sure before returning that the thread has finished - easiest way is th.join(). This method waits for the thread to die.

Categories

Resources