我正在编写一个企业 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 方法调用是否有更好的选择?