views:

117

answers:

1

Hello everyone, I have a question. Is it possible to implement a background process in a servlet!?

Let me explain. I have a servlet that shows some data and generate some reports. The generation of the report implies that the data is already present, and it is this: someone else upload these data.

In addition to report generation, I should implement a way to send an email on arrival of new data (uploaded). Making this possible? Thanks in advance for any suggestions,

A: 

The functional requirement is unclear, but to answer the actual question: yes, it's possible to run a background process in servletcontainer.

If you want an applicationwide background thread, use ServletContextListener to hook on webapp's startup and shutdown and use ExecutorService to run it.

public class Config implements ServletContextListener {

    private ExecutorService executor;

    public void contextInitialized(ServletContextEvent event) {
        executor = Executors.newSingleThreadExecutor();
        executor.submit(new Task()); // Task should implement Runnable.
    }

    public void contextDestroyed(ServletContextEvent event) {
        executor.shutdown();
    }

}

with in web.xml:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

If you want a sessionwide background thread, use HttpSessionBindingListener to start and stop it.

public class Task extends Thread implements HttpSessionBindingListener {

    public void run() {
        while (true) {
            someHeavyStuff();
            if (isInterrupted()) return;
        }
    }

    public void valueBound(HttpSessionBindingEvent event) {
        start(); // Will instantly be started when doing session.setAttribute("task", new Task());
    }

    public void valueUnbound(HttpSessionBindingEvent event) {
        interrupt(); // Will signal interrupt when session expires.
    }

}

On first creation and start, just do

request.getSession().setAttribute("task", new Task());
BalusC
Thank you for your replay.Sorry. The request asked me is to implement a way to send email (an alert) when some data uploaded (new data loaded in DB). I had thought to implement this mechanism by modifying existing web application, creating background process that polling on new data. The data are loaded by some other application that I don't manage. Servlet container is Tomcat.Thanks for answers
sangi
Why don't you just write this directly after the piece of code which updates the data in DB?
BalusC
Because I have not access to application that loads data: it is managed and developed by other people that I can't reach.
sangi