小编mal*_*loc的帖子

取消@Asynchronous EJB调用

我正在编写一个企业Java应用程序,它使用异步EJB 3.1方法并行执行许多任务.为了支持取消长时间运行的任务,我一直在尝试使用Future接口.

不幸的是,future.cancel(true)从客户端应用程序调用似乎对执行任务的bean的会话上下文没有影响,尽管取消调用正在返回true.

我有一个简单的界面:

public interface AsyncInterface
{
    Future<Integer> run() throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

使用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);
     }
}
Run Code Online (Sandbox Code Playgroud)

客户端代码很简单:

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 …
Run Code Online (Sandbox Code Playgroud)

java asynchronous ejb java-ee ejb-3.1

7
推荐指数
1
解决办法
5634
查看次数

标签 统计

asynchronous ×1

ejb ×1

ejb-3.1 ×1

java ×1

java-ee ×1