【发布时间】:2011-06-14 06:59:38
【问题描述】:
我正在编写一个企业 Java 应用程序,它使用异步 EJB 3.1 方法来并行执行多个任务。为了支持取消长时间运行的任务,我一直在尝试使用 Future 接口。
不幸的是,从客户端应用程序调用 future.cancel(true) 似乎对执行任务的 bean 的会话上下文没有影响,尽管取消调用正在返回 true。
我有一个简单的界面:
public interface AsyncInterface
{
Future<Integer> run() throws Exception;
}
使用bean实现如下:
@Stateless
@Remote(AsyncInterface.class)
public class AsyncBean
{
@Resource SessionContext myContext;
@Asynchronous
public Future<Integer> run() throws Exception
{
Integer result = 0;
System.out.println("Running AsyncBean");
while(myContext.wasCancelCalled() == false)
{
Thread.sleep(2000);
System.out.println("Working");
}
System.out.println("AsyncBean cancelled");
return new AsyncResult<Integer>(result);
}
}
客户端代码很简单:
InitialContext ctx = new InitialContext();
AsyncInterface async = (AsyncInterface)ctx.lookup("AsyncBean/remote");
Future<Integer> future = async.run();
if( future.cancel(true) )
{
System.out.println("future.cancel() returned true");
}
else
{
System.out.println("future.cancel() returned false");
}
bean 的输出是源源不断的“Working”;它永远不会检测到取消。
如果相关,我将在 JBoss Application Server 6.0.0 上运行该应用程序。我没有找到太多使用 Future 接口的取消功能的示例代码,所以我想知道我是否正确使用了 Future。这种用法看起来正确吗?取消异步 EJB 方法调用是否有更好的选择?
【问题讨论】:
-
这是一种奇怪的行为,因为如果取消方法返回 true,则表明您的会话 bean 方法将不会被调用(原因是当您调用取消时,该方法可能已经在运行)。您可以在 EJB 3.1 规范的第 3.4.8.1.1 节中查看更多信息。
-
将此链接到类似问题,但适用于 glassfish stackoverflow.com/q/16493381/3701228
标签: java asynchronous jakarta-ee ejb ejb-3.1