gpt4 book ai didi

java - 如何使用 servlet 运行长时间运行的进程

转载 作者:行者123 更新时间:2023-12-01 09:36:16 25 4
gpt4 key购买 nike

我遇到了一种情况,我需要启动一个运行 4 小时的任务。我正在使用 servlet 来启动该过程。但是我遇到了内存泄漏异常。

Aug 10, 2016 2:08:05 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/] has started
Aug 10, 2016 2:08:05 PM org.apache.catalina.core.StandardWrapper unload
INFO: Waiting for 1 instance(s) to be deallocated for Servlet [Servlet]
Aug 10, 2016 2:08:06 PM org.apache.catalina.core.StandardWrapper unload
INFO: Waiting for 1 instance(s) to be deallocated for Servlet [Servlet]
Aug 10, 2016 2:08:07 PM org.apache.catalina.core.StandardWrapper unload
INFO: Waiting for 1 instance(s) to be deallocated for Servlet [DayZeroServlet]
Aug 10, 2016 2:08:07 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
WARNING: The web application [xxx#Day0MS] is still processing a request that has yet to finish. This is very likely to create a memory leak. You can control the time allowed for requests to finish by using the unloadDelay attribute of the standard Context implementation. Stack trace of request processing thread:
java.net.SocketOutputStream.socketWrite0(Native Method)
java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)

下面是我正在使用的代码

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
if (!GehDAO.getProcessFlag()) {
GehDAO.updateProcessFlag(true);
out.println("Transformation started ...");
closeWriter(out);
execute(); // This step start the long running process
}
else {
out.println("Transformation Already Running ...");
closeWriter(out);
}
}

有没有办法在单独的进程中运行execute()方法?

我想在一个月内运行这个 servlet 一两次,以启动长时间运行的进程。

最佳答案

不能将 execute() 调用包装到线程中吗?

new Thread(() -> execute()).start();

或者对于较旧的 Java8 之前的版本:

new Thread(new Runnable() {
public void run() { execute(); }
}).start();

附注:确保您能够管理关闭。您通常可以使用 ServletContextListener 来执行此操作。基本上,如果上下文被破坏,请在长时间运行的线程上设置一个 boolean 标志,让它知道它需要停止,因为应用程序服务器正在等待它完成才能关闭。

关于java - 如何使用 servlet 运行长时间运行的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38882268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com