1 Reply Latest reply on Jul 8, 2014 12:58 PM by matthias.lathe

    How to Intercept all @Asynchronous methods

    matthias.lathe

      Hi,

      I'm looking for a nice way to intercept all Asynchronous methods in 2.2.0.GA. Most of my Asynchronous methods look like this: basically a method that takes a job, and does work on that job

       

      public class PaymentHandler {
        @Asynchronous
        public void addItem(Job job, Item item) {
          job.addStep("adding item");
          //add item
          job.update("success");
        }

        @Asynchronous
        public void removeItem(Job job, Item item) {
          job.addStep("removing item");
          //remove item
          job.update("success");
        }
      }

       

      The problem is that if these methods are not "closed" due to an Exception or just programmer error the user is left wondering what happened to the job. This has led to a anti-pattern of wrapping the body of each method is a "wide try catch" to give a chance to mark the job as failed. This is error prone and not ideal. I'd like a single place that does this kind of cleanup

       

      It appears that one solution is to write a AsynchronousExceptionHandler, but the "invocation" of the method is lost, so there is no way to get a handle on the job object to apply some logic.

       

      Another solution I've tried is to implement my own ThreadPoolDispatcher, which would give me a chance to override the RunnableAsynchronous class which appears to be the thing that actually spawns the new thread. In there I could then add a finally block to do what I need.

       

      static class RunnableAsynchronous implements Runnable {

      //snip//
            public void run()
            {
               try
               {
                  async.execute(future);
               }
               catch (Exception exception)
               {
                  async.handleException(exception, future);
               }

               //Add the finally here!!!

            }

      }

       

      Is there a better way to do this?