开发者

Can synchronization be treated as an aspect in AOP

I understand that in AOP any cross cutting concerns such as Logging, trans开发者_StackOverflowaction etc can be treated as an aspect and most of the AOP frameworks very well support these kind of cross-cutting concerns.

My question is,

  • Can Synchronization be treated as a crosscutting concern ?
  • If yes, are there any existing libraries (including AspectJ and Spring AOP) which support this functionality out of box ?

I searched but could not find many examples. I came across some restricted research papers (1,2) though.


Just a theoretical "answer". :)

As I understand AOP, you add independent behaviours/"advices" to some "pointcuts"/"joint points". But synchronization is intended to be used tightly related with a code it manages.

I guess the way to use synchronization is if it will be attached as advice and will provide itself as a "joint point" for which other "aspects" will define some "advices".

Or you might get some kind of synchronization inside your "advices" while trying to call some "joint points".


In theory it's possible to have an AOP framework which adds synchronization to a set of methods/classes. It's not even hard to implement. But it is usually not what you want. Too much synchronization is just as bad as too few synchronization, because you either run into deadlocks or you sequentialize your threading so much, that you are not able to use multiple cores effectively.

I am afraid there is no no brainer shortcut to multithreaded programming.


Yes, synchronisation can be treated as an aspect. Isn't the idea behind AOP to handle cross cutting concerns? Then, regarding synchronisation as a cross cutting concern can be handled via AOP without defining and using external libraries.

Consider the following example about read-write locking. Whenever an object is subject to be read/write, then you can capture the method and provide sufficient functionality for concurrency control.

public abstract aspect ReadWriteLockSynchronizationAspect 
    perthis(readOperations() || writeOperations()) {

    public abstract pointcut readOperations();

    public abstract pointcut writeOperations();

    private ReadWriteLock _lock = new SomeReadWriteLock();

    before() : readOperations() {
        _lock.readLock().acquire();
    }

    after() : readOperations() {
        _lock.readLock().release();
    }

    before() : writeOperations() {
        _lock.writeLock().acquire();
    }

    after() : writeOperations() {
        _lock.writeLock().release();
    }
}

perthis creates a new aspect for each read/write operation. Otherwise, only one aspect will be created and it works like a singleton object. For further information check AspectJ in Action.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜