【发布时间】:2014-03-04 08:32:01
【问题描述】:
我的 Web 应用程序(在 Tomcat 上)提供“动态”逻辑执行功能。
问题是“on the fly”逻辑可能包含无限循环,或者持续时间很长的东西。
我的解决方案是超时:在一个新的守护线程中运行“on the fly”逻辑,超时返回主线程,p-code如下:
ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory(){
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
result.setDaemon(true);
return t;
}});
Future<Object> future = executor.submit(callable/* 'on the fly' callable: it can be infinite loop, the callable is out of my control */);
//Back to main thread
return future.get(timeout, TimeUnit.MILLISECONDS);
然而,守护线程仍在运行,尽管future.get() 超时返回。守护进程将终止,直到 Tomcat 停止。
现在我最新的解决方案是创建一个新的 Java 进程 Runtime.getRuntime().exec("java MyProgram")。 MyProgram 包含之前显示的future.get()。一旦主线程按预期退出,守护程序就会终止。
我在这里要求更优雅的解决方案来终止 Web 应用程序中的线程。新的 Java 进程很重,并且无法控制 Web 应用程序。
谢谢!
【问题讨论】:
标签: java multithreading jvm