在Tomcat中运行后台Java程序 [英] Running a background Java program in Tomcat

查看:207
本文介绍了在Tomcat中运行后台Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在这里提出建议吗?我有这种情况,用户将通过Java JSP和servlet以交互方式向我的应用程序提交数据挖掘请求,该应用程序将动态地计算出关于数据的关联规则等。

Can anyone advise here? I have a situation where users will submit data mining requests interactively via a Java JSP and servlet to an application of mine which will dynamically work out association rules on data and more.

由于这样的工作可能需要一段时间,我正在考虑服务器上的某种过程在后台运行这样的请求所以它不会'锁定会话并可能使用大量服务器内存而不利于系统。

As such a job may take a while, I'm thinking of some sort of process on the server to run such a request in the background so it dosen't 'lock' the session and possibly use massive amounts of server memory to the detriment of the system.

由于系统由一系列运行的Java JSP和servlet组成MySQL数据库上的Tomcat容器,任何人都可以建议前进的方向吗?

As the system is made up of a series of Java JSPs and servlets running in a Tomcat container over a MySQL database, can anyone advise a way forward?

谢谢

Mr Morgan

Mr Morgan

推荐答案

使用 ExecutorService

你应该做一些事情,将线程标记为守护进程线程因此它至少不会在错误情况下占用tomcat,并且应该在servlet上下文被销毁时停止执行程序(例如,当您重新部署或停止应用程序时。为此,请使用ServletContextListener:

There's a few things you should do though, mark the thread as a daemon thread so it atleast won't tie up tomcat in error scenarios, and you should stop the executor when your servlet context is destroyed (e.g. when you redeploy or stop your application. To do this, use a ServletContextListener:

public class ExecutorContextListener implements ServletContextListener {
    private  ExecutorService executor;

    public void contextInitialized(ServletContextEvent arg0) {
        ServletContext context = arg0.getServletContext();
        int nr_executors = 1;
        ThreadFactory daemonFactory = new DaemonThreadFactory();
        try {
            nr_executors = Integer.parseInt(context.getInitParameter("nr-executors"));
        } catch (NumberFormatException ignore ) {}

        if(nr_executors <= 1) {
        executor = Executors.newSingleThreadExecutor(daemonFactory);
        } else {
        executor = Executors.newFixedThreadPool(nr_executors,daemonFactory);
       }
          context.setAttribute("MY_EXECUTOR", executor);
      }

    public void contextDestroyed(ServletContextEvent arg0) {
        ServletContext context = arg0.getServletContext();
        executor.shutdownNow(); // or process/wait until all pending jobs are done
    }

}
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * Hands out threads from the wrapped threadfactory with setDeamon(true), so the
 * threads won't keep the JVM alive when it should otherwise exit.
 */
public class DaemonThreadFactory implements ThreadFactory {

    private final ThreadFactory factory;

    /**
     * Construct a ThreadFactory with setDeamon(true) using
     * Executors.defaultThreadFactory()
     */
    public DaemonThreadFactory() {
        this(Executors.defaultThreadFactory());
    }

    /**
     * Construct a ThreadFactory with setDeamon(true) wrapping the given factory
     * 
     * @param thread
     *            factory to wrap
     */
    public DaemonThreadFactory(ThreadFactory factory) {
        if (factory == null)
            throw new NullPointerException("factory cannot be null");
        this.factory = factory;
    }

    public Thread newThread(Runnable r) {
        final Thread t = factory.newThread(r);
        t.setDaemon(true);
        return t;
    }
}

您必须将上下文监听器添加到您的web.xml,您还可以在其中指定要运行后台作业的线程数:

You'll have to add the context listener to your web.xml, where you also can specify the number of threads you'll want to run the background jobs:

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

您可以从servlet访问执行程序并向其提交作业:

You can access the executor from your servlet and submit jobs to it:

ExecutorService executor = (ExecutorService )getServletContext().getAttribute("MY_EXECUTOR");
...
executor.submit(myJob);

如果您使用的是Spring,那么所有这些甚至可能都是更简单

If you're using Spring, all this can probably be made even simpler

这篇关于在Tomcat中运行后台Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆