Wednesday, February 15, 2012

Transactions as an Aspect

Documents that introduce AOP use the same examples when describing its practical applications.  The first two, in this order, are always:
  • Logging
  • Transactions
And indeed, you can treat transactions, in particular database transactions, as an aspect.  Your business object is kept blissfully unaware that it is wrapped by a proxy that is executing it within a transaction.

However, in multi-threaded environments, business object must also perform synchronization.  That is, when performing an operation the business object must guarantee it's not accessing shared data with itself on a different thread.  To prevent this, it must acquire object locks.  Since the locks are private (as they should be, to preserve encapsulation) to the object in question, and because how or what locks are acquired may change depending upon the method parameters and/or logic, it is up to each individual public object operation to perform the locking.

When an operation on an object with a transaction aspect applied the transaction would start first, then the object locks would be acquired.  This is a problem because you never want to start a database transaction first.  If an object lock takes longer to acquire than a database transaction is long the operation will fail.  Instead, we want to acquire object locks first, then begin the transaction.

This would seem to indicate that transactions can't be represented as an aspect.  However, we won't give up quite yet.  One could argue that the synchronization I described could also be captured as an aspect.  You could apply both aspects to the business object so long as you ensure the synchronization aspect is a layer above the transaction aspect.  But can the synchronization aspect have enough knowledge to understand what locks to acquire?  Would it not have to duplicate logic already present in the business object?  How would this fit into a design that cached data access which had to acquire its own locks?  Would we not be setting ourselves up for deadlocks?

No comments:

Post a Comment