stopping threads gracefully - java

I am using ScheduledExecutorService for scheduling a thread. I wonder what happens when JBoss is shut down? Does it kill all the threads that are started within the server, including the the one I scheduled? Do I have to do it manually using ScheduledFuture, and cancel the thread when ServletContext is destroyed?

There are two methods:
java.util.concurrent.ExecutorService.shutdown()
java.util.concurrent.ExecutorService.shutdownNow()
JBoss won't call any of these unless you do it in method which will be called upon shutdown. For web applications you have the chance to do it in javax.servlet.ServletContextListener.contextDestroyed(ServletContextEvent).
Of course this is the JavaEE/Servlets way. You can hide it by using e.g. Spring Framework. By creating org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler you'll get shutting down for free (this class implements org.springframework.beans.factory.DisposableBean). See the details here.

Related

When is contextDestroyed called?

Having implemented a ContextListener I can now happily deal with contextDestroyed events by closing down my connection pools and flushing my caches etc.
I was surprised recently when contextDestroyed was called at a time when my server was not being shut down - it seemed to be at some arbitrary time which I have not been able to track down.
Is there any defined event or set of circumstances that trigger contextDestroyed?
Should I ensure that everything I do when contextDestroyed is called is reversible? Do I need to make all my pools survive a destroyed/initialized cycle? Was I wrong to assume I would only get a contextDestroyed when Tomcat was being shut down or my war was being replaced?
Through a series of trial and error testing I have found that contextDestroyed() is called when;
The server is .WAR is being updated/removed.
The server is shutdown due to administrator intervention.
The server is shutdown due to a coding error. Something that would
terminate a non-server application termination.
If you are experiencing issue #3, as you are suggesting, I think the best possible course of action is to safely (be sure not to create an infinite loop) call contextInitialized() to ensure pools are recreated properly.
See: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html
contextDestroyed(ServletContextEvent sce): Receives notification that
the ServletContext is about to be shut down.
I.e., it gets called when a web application gets unloaded (e.g., you remove or replace a .war file from the web-apps folder OR unload it using the Tomcat server-manager).

How to check whether #Schedule annotation (Spring 3.1) cron job is running.

In my application I have one cron job which connects to a FTP server and transfer files, a very simple functionality and it is configured using spring #Schedule annotation with cron expression as a parameter.
It was running fine for few months and then suddenly it stopped, got the connectException.
May be the FTP server was down or something happened which causes the cron thread to stop.
I looked (google) for the reasons but didnt get any ( Nothing much in the logs also - Just the exception name ).It may be a one time thing :)
my question is that can I put some check or watcher on the #Schedule cron job to know whether it is running or not ?
Sorry for my bad explanation/english
Thanks
my question is that can I put some check or watcher on the #Schedule
cron job to know whether it is running or not ?
Basically, you can't.
When you use #Scheduled, Spring uses a ScheduledAnnotationBeanPostProcessor to register the tasks you specify (annotated methods). It registers them with a ScheduledTaskRegistrar. The ScheduledAnnotationBeanPostProcessor is an ApplicationListener<ContextRefreshEvent>. When it receives the ContextRefreshEvent from the ApplicationContext, it schedules the tasks registered in the ScheduledTaskRegistrar.
During this step, these tasks are scheduled with a TaskScheduler which typically wraps a ScheduledExecutorService. If an exception is uncaught in a submitted task, then the task is removed from the ScheduledExecutorService queue.
The TaskScheduler class does not provide a public API to retrieve the scheduled tasks, ie. the ScheduledFuture objects. So you can't use it to find out if your tasks are running or not.
And you probably shouldn't. Develop your tasks, your #Scheduled methods, to be able to withstand an exception being thrown. Some times, obviously, that's not possible. With a network error, for example, you would probably have to restart your application. Without knowing anything else about your application, I would say more logging is your best bet.

Call method after JBoss deploy

I want to have some method run, only after my WAR has been deployed to JBoss.
The problem: Currently I am using #PostConstruct to load saved schedules from the DB. The problem is that I am creating instances of the Schedulers from this method, which in turn is starting the Quartz schedulers, which is stopping JBoss from completing the deploy.
If there are no schedules to load, my WAR deploys fine, but if there are schedules they are causing the deploy to fail, because JBoss is "waiting" for the schedules to actually complete.
Is there some way to delay the method call until after it is fully deployed?
Or alternatively, is it possible to make Async calls on the Server (from the Server code)?
Java EE specification heavily refrain any thread manipulation outside facility provided by the application server.
You shouldn't in any case use a container manged thread in an infinite loop; the container expect the thread to be returned. Thread creation can still be done without too much collateral damage (if you don't put several apps on the server as the container won't be able to manage the resources between all the applications) but the any container thread must be returned.
In the new Jboss 7 there is some Java EE scheduling facilities (#Scheduling and timer, with possible persistent timer). A quick search show some example how to run Quartz in JBoss 7: How to enable Quartz scheduling in Jboss AS 7.0?
In older JBoss more advanced integration exist (JCA integration is the only standard way to get finer thread management). Use google to find them.
Wouldn't the simple ServletContextListener solve the problem for you? Just implement whatever you need in contextInitialized method.
In JBoss 7, there is a management api.
Maybe you can use it to check if the server is started (with a singleton and a TimerService).
Sample code:
ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9999);
ModelNode op = new ModelNode();
op.get(ClientConstants.OP).set("read-attribute");
op.get(ClientConstants.NAME).set("server-state");
ModelNode returnVal = client.execute(op);
if(StringUtils.equals(returnVal.get("result").toString(), "\"running\"")){
LOGGER.info("Server running, init start actions");
timer.cancel();
}else{
LOGGER.info("Server not running, wait");
}

Design Pattern to correctly exit a running program from multiple locations

I have a system written in java where I have multiple distinct objects each with different resources in use. Some have connections to activeMQ queues, some have network connections and others have open files. Some also contain running threads.
When a fatal error occurs anywhere in this system, I need to shut it down and correctly close all resources and stop all running threads.
My problem arises when the object that caused the error needs to start the shutdown process. This object does not know about the other objects that have open files and so on. So it can basically release all its resources and that is it.
I am looking for a clean way to achieve this without getting messy and passing multiple object references around the system.
Any insight is appreciated. Thank you.
Create a central Lifecycle object which all of these other objects in your application have a reference to, and which in turn has a reference to all of these other objects. In addition, each of these objects should implement a common interface such as
public interface ShutdownListener {
void onShutdown();
}
When one of the objects needs to start an orderly shutdown, it can call lifecycle.shutdown() which can in turn call object.onShutdown() on all of the objects registered with it, in order to give these objects a chance to close their resources.
This is basically the Observer pattern.
If you use a dependency-injection container such as Spring, this type of thing is built-in - your beans can extend a certain interface to be notified when the container is shutting down.
You may be able to use Shutdown hook for that. In it you can notify all related objects, which, of course, need to be registered somewhere.
A java virtual machine allows the registration of Shutdown Hooks. Your database connection pool, your file IO manager, your activeMQ queues manager can all independently register their own shutdown hooks that each close all their resources cleanly.
A shutdown hook is a Thread that requires a reference to the resource manager(s) it's responsible for shutting down. The run method of this thread will be executed when the application is terminated. Your application has access to register a shutdown hook anywhere as Runtime.getRuntime() is available as a static call, so no need to wire it into the areas of the application that need it (although it is advisable that you register such shutdown hooks at the time of the creation of each resource manager).
More information here.
http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

Shutting down a TaskExecutor in a web application when the web server is shutdown

I have a web application that makes use of a Spring TaskExecutor. The task executor is started when the web application is loaded for the first time and the thread runs the entire life of the web application. Ever since I added this thread to the application, Oracle Application Server will no longer shutdown gracefully. My guess is that OAS is not shutting down because I am not gracefully shutting down the task executor thread anywhere in the code. Where would the best place be to shutdown the task executor in a web application? I am using Java 5 with Spring 2.5.6.
Here is the task executor that I am using:
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>
SimpleAsyncTaskExecutor has no meaningful state, it does not require shutting down gracefully. Also, I'm not sure what you mean by "the thread runs the entire life of the web application" - which thread are you referring to?
However, the threads that it spawns may be preventing your server from shutting down. SimpleAsyncTaskExecutor uses a ThreadFactory to create its threads, and by default threads that are created are not daemon threads, and so any spawned threads which are still executing when the shutdown is initiated will continue, and the server will only terminate when all of those spawned threads are finished.
As a solution, I suggest using a ThreadPoolTaskExecutor in preference to the SimpleAsyncTaskExecutor. This has a boolean property which controls what happens when a shutdown occurs, and it can force the termination of the thread pool if required.
If you still want to use SimpleAsyncTaskExecutor, then you could inject it with a custom ThreadFactory which creates deamon threads. This will allow the server to shutdown regardless of the state of those spawned threads. This might be dangerous, though, if those threads could leave resources in an unstable state.
Spring provides a bean-friendly implementation of ThreadFactory (CustomizableThreadFactory) which you can inject into the SimpleAsyncTaskExecutor, setting the daemon property to false.
Typically web aplications can react to container shutdown via a ServletContextListener. Implement one and use it to shut down your Executor. Ideally you should couple that with a proper shutdown of the whole Spring lifecycle. I vaguely remember that Spring had something ready-made for that purpose, so it's probably a good idea to check there as well.
You can use the #PreDestroy annotation:
#PreDestroy
protected void shutDown() {
taskExecutor.shutdown();
}

Categories