3

How I can provide a timeout execution to a Spring AOP Aspect ?

The logger method of MyAspect shouldn't take more time execution than 30 seconds, if not i would want to stop the method execution. How i can do this ?

MyAspect Code :

@Aspect
@Component
public class MyAspect {

     @Autowired
     private myService myService;

     @AfterReturning(pointcut = "execution(* xxxxx*(..))", returning = "paramOut")
     public void logger(final JoinPoint jp, Object paramOut){
         Event event = (Event) paramOut;
         myService.save(event);
     }
}

myService Interface :

public interface myService {
    void save(Event event);
}

myServiceImpl :

@Service
@Transactional
public class myServiceImpl implements myService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void save(Event event) {
        entityManager.persist(event);
    }
}
user2602584
  • 737
  • 2
  • 7
  • 25

1 Answers1

2

Use java.util.concurrent.Future to check the timeout. See next example:

@AfterReturning(pointcut = "execution(* xxxxx*(..))", returning = "paramOut")
public void logger(final JoinPoint jp, Object paramOut){
     Event event = (Event) paramOut;

     ExecutorService executor = Executors.newSingleThreadExecutor();

     Future<Void> future = executor.submit(new Callable<Void>() {
         public Void call() throws Exception {
            myService.save(event);
            return null;
        }
    });

    try
    {
        future.get(30, TimeUnit.SECONDS);
    }
    catch(InterruptedException | ExecutionException | TimeoutException e){
       //do something or log it
    } finally {
       future.cancel(true);
    }

 }
Pau
  • 14,917
  • 14
  • 67
  • 94
  • Thanks for your replay, it looks like right, but can you plz explain it ? what about if the Call method take more than 30 seconds, it will be interrupted ? – user2602584 Sep 02 '16 at 15:17