Replace the After Advice with a Finally Advice
To illustrate the usability of finally advices, lets revisit the example of before/after advices. In that example, we wrote a MutexAspect to assure that several concurrent bank transactions could be run in a synchronized manner. The MutexAspect was composed by a pair of related before/after advices. The before advice would retrieve the mutex lock, that would be later released by the after advice: public class MutexAspect { private Object lock = new Object(); private boolean locked = false; public void beforeAdvice(@JoinPoint Joinpoint joinPoint) { synchronized(lock) { while (locked) { try { lock.wait(); } catch(InterruptedException e) { Thread.currentThread().interrupt(); return; } } locked = true; System.out.println(">>> Retrieved concurrency lock"); } } public void afterAdvice(@JoinPoint Joinpoint joinPoint) { synchronized(lock) { locked = false; lock.notify(); System.out.println(" < < < Releasing concurrency lock"); } } } ___________________________ But after advices are not assured to be executed always. If an exception is thrown during a transaction execution, the after advice will not be invoked, impeding the lock from being released, and locking the other threads. To avoid that situation, we should replace afterAdvice by a finally advice. Differently from the first, the finally advice will be executed always, avoiding a deadlock caused by an exception in one thread. Replacing the after advice in the example above is simple: public class MutexAspect { private Object lock = new Object(); private boolean locked = false; public void beforeAdvice(@JoinPoint JoinPointBean joinPoint) { synchronized(lock) { while (locked) { try { lock.wait(); } catch(InterruptedException e) { Thread.currentThread().interrupt(); return; } } locked = true; System.out.println(">>> Retrieved concurrency lock"); } } public void finallyAdvice(@JoinPoint JoinPointBean joinPoint) { synchronized(lock) { locked = false; lock.notifyAll(); System.out.println("<<< Releasing concurrency lock"); } } } ___________________________ To show the finally mechanism in action, we slightly changed the bank application, by throwing an exception when a transaction results in an negative balance.