5 Replies Latest reply on Feb 15, 2011 6:57 PM by david_b

    Cancelling an @Asynchronous method with Future.cancel

    david_b Newbie

      I am writing an enterprise Java application that uses aynchronous EJB 3.1 methods to execute a number of tasks in parallel. The app is currently running on JBoss AS 6.0.0 Final.

       

      To support cancelling a long running task I have been attempting to use the Future interface. Unfortunately calling future.cancel(true)appears to have no effect on the session context of the bean executing the task, despite the fact that cancel is returning true.

       

      I have a simple interface:

       

      {code}public interface AsyncInterface
      {
          Future<Integer> run() throws Exception;
      }{code}

       

      With a bean implementation as follows:

       

      {code}@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(1000);

                  System.out.println("Working");

              }     


              System.out.println("AsyncBean Cancelled");

              return new AsyncResult<Integer>(result);

          }

      }

      {code}

       

      The asynchronous method is called from another Stateless EJB like so:

       

      {code}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");

      } {code}

       

      The output from the AsyncBean is an endless stream of "Working"; it never detects the cancellation.

       

      I haven't found much sample code using Futures to cancel an @Asynchronous EJB call. Is using the session context the correct way of checking for cancellation? Is there a better method for cancelling the asynchronous call?