AOP and Aspectj
Mountain bridge http://www.jdon.com 2004/01/10
Demand and problem
Multiple access classes When accessing a shared data object, each access class When accessing this data object, you need to lock the data object. After the access is completed, unlock it, it is for other concurrent threads. The way of resources.
In order to achieve this need, first implement traditional programming, here we assume that there is a write lock, before writing the data object, first write the object on this object, after the write operation is completed, the write lock must be released.
First, we need a lock that can be a field or other in the data object, here using the Doug Lea's ReentrantWriterPreferenceReadWritelock as our lock resource.
import EDU.oswego.cs.dl.util.concurrent *;. public class Worker extends Thread {Data data; ReentrantWriterPreferenceReadWriteLock rwl = new ReentrantWriterPreferenceReadWriteLock (); public boolean createData () {try {rwl.writeLock () acquire ().; // Lock // Retrieve the write logic operation} catch () {rwl.writelock (). Release (); // Unlock} returnly;} public boolean updata ()} public boolean updata ()} public boolean updata ()} .writelock (). acquire (); // Lock / / write logic operation} catch () {rwl.writelock (). Release (); // unlock} return true;} Public void run () {// execute createdata () or Updatedata ()}}}}}
Suppose there is a different access class, which will also implement the data object, the code is as follows:
import EDU.oswego.cs.dl.util.concurrent *;. public class AnotherWorker extends Thread {Data data; ReentrantWriterPreferenceReadWriteLock rwl = new ReentrantWriterPreferenceReadWriteLock (); public boolean updateData () {try {rwl.writeLock () acquire ().; // Locked // The write logic operation is implemented to the DATA} catCH () {RTURN FALSE;} finally {rwl.writelock (). Release (); // Unlock} return true;} public void run () {// execution Updatedata ()}}}
The above is the implementation of Java traditional programming, this lock is implemented in each specific class, as shown below:
There are many shortcomings in this implementation:
Redundancy: There are many duplicate encodings, such as rwl.writelock (). Acquire (), etc .; Reduce reuse: Worker's updatedata () method reuse is almost zero. "Data object write operation must be used to control this design" Not easy to appear. If a new programmer is replaced, he may write a code that does not write the data object if the lock mechanism is written. If the above code has a read function, then we need to implement the lock first in the code. When you need to write, interrogate the lock, then write the lock, etc., if you are not careful, the lock unlocking order is wrong, the system is implied Large bug, this possibility will always exist in this data object, the system design is much hidden! Then we use the AOP concept to reach the above needs, AOP does not have any new tricks, just provide a new perspective of observation issues.
Here we can throw new technologies and fascinating, new thinking, new perspectives, many problems in human beings, maybe for a brain, maybe it is true, so, as a person, first, we must pay attention to Your world-view and way of thinking are unlike people to communicate and communicate.
There are many "unfair" in real life. For example, a primary school graduate has produced thousands of people. You will suspect that knowledge is useless. Maybe you think he is good, in fact, you may not know, his view is better than you Unique, or he may often change the problem and solve the problem, and you lose the true direction due to the specific implementation details of excessive perspective, or not to say that the brain is a brainness?
For the words, we look at how the AOP solves the above problems from a new perspective.
If the above code implements the lock or unlock in each class, similar to the horizontal solution, the AOP is a longitudinal aspect to solve the above problem, and the longitudinal solution is as follows:
AOP calls this longitudinal section Cross-Cuts as ASPECT (aspect), in fact, I think AOP translation is better for cutting-faced programming, I don't know which confused person is translated into "facing aspects" so abstract, so I am imaginary.
Aspectj implementation
Below we use one of the AOP implementation aspect to rewrite the above needs. Aspectj is the earliest Java implementation of AOP, which extends slightly, and adds some Keyword et al., Pointcut's syntax is as follows:
Public PointCut method name: Call (xxxx)
Aspectj adds PointCut, Call is the PointCut type, and sees here for AspectJ more basic syntax. Because aspectj uses some special syntax, the Java compiler cannot use Sun to provide Javac, and you must use its specialized compiler, and maybe Sun will introduce AOP in the later JDK version.
How to use AspectJ to implement the above-called cut surface programming? First, we will be called aspect, then we build a class-like Aspect, and establish a Class code in Java as follows:
Public class myclass {// attributes and methods ...}
Similarly, the code to establish an aspect is as follows:
Public aspect myaspect {// attributes and methods ...}
Create an Aspect named LOCK, the code is as follows:
import EDU.oswego.cs.dl.util.concurrent *; public aspect Lock {...... ReentrantWriterPreferenceReadWriteLock rwl = new ReentrantWriterPreferenceReadWriteLock (); public pointcut writeOperations (): execution (public boolean Worker.createData ()) |. | Execution (publicilean worker.updatedata ()) || exec (): writeOperations (): writeOperations () {rwl.writelock (). Acquire (); // Lock Advice Body }After (): writeOperations () {rwl.writelock (). Release (); // Unlock Advice Body} ...} The above code key is PointCut, meaning entry point or trigger point, then in those conditions Have you trigger it? It is some cases of the red word logo, triggered when executing the Createdata () method of the worker, the worker UPDATE method, etc.
What do Before doing before the trigger? The answer is to lock.
What does the AFTER do after the representative trigger? The answer is to lock.
The WORKER code can be cleaned by introducing the above aspect, then the WORKER code is cleaned:
Public class worker extends thread {data data; public boolean createData () {Try {// write logic to DATA () {Return False;} return true;} public boolean updata () {TRY {// Pair Data Retrieve write logic operation} catch () {return false;} finally {} return true;} public void run () {// execute createdata () or Updatedata ()}
The code about "lock" is gone, purely into the main method of data operation.
AOP terminology
Through the previous example, aspectj has been known from the cut-faced crosscutting to resolve and send application requirements, the most important thing is to introduce a similar event trigger mechanism.
PointCut-like trigger is an event event generation source. Once PointCut is triggered, the corresponding action action will be generated, which is called Advice.
Advice has three types: Before, After, Around, the two Before and After the ADVICE is used in the Aspect Lock code.
So AOP has two basic terms: Pointcut and Advice. You can use event mechanisms to understand them. PointCut and Advice are shown below: PointCut and Advice are shown below:
Summary is as follows: Advice - real execution code, or the implementation of attention. Similar Action. The Join Point - A trigger point that activates the Advice executed in the code. Pointcut - a series of Join Point called Pointcut, Pointcut Saves a generation of Join Point
The Advice section is: the interceptor-interpreter does not appear in AspectJ, use the AOP framework implemented by the JDK dynamic agent API, explain the events such as method calls or object constructs or field access, which is the caller and the caller. The link between the Decorator / Agent mode is integrated. Introduction - Modify a class to add fields, methods, or constructs or perform new interfaces, including Mixin implementation.
For example, in the above-described concurrent access application, if you want to generate the corresponding Aspect Lock for each Data object, you can add a field LOCK in the ASPECT LOCK, as follows:
Aspect lock {data shareddatainstance; lockstance = d;} Introduce lock data.lock; // Modify the DATA class, add a field lock advise data () {// Data constructor triggered static instance {// When the Data object is generated, the LOCK field in DATA is assigned aspect lock // generate the corresponding aspect lock thisobject.lock = new lock (thisobject) for each Data object;}} ....
The above code is equal to joining a line in the DATA class:
Public class data {... loc Lock = new lock (); ......}
There are other two ways involving AOP code:
Weaving - Insert the Aspect code into the corresponding code, which is generally compiled or done during runtime. Depending on the specific AOP product, such as AspectJ is using a special compiler to compile Weaving, and Nanning, JBoss AOP is using dynamic agent API, so dynamically complete Weaving during runtime. INSTRUMENTOR - Tools used to implement Weaving feature.
Reference:
Http://today.java.net/pub/A/today/2003/12/26/ch3ampctjsyntaxbasics.html
http://www.theserverside.com/resources/Article.jsp?l=aspectorientedRefactoringPart1
http://www.voelter.de/data/articles/aop/aop.html
http://nanning.snipsnap.org/space/interceptor
There is already a lot of AOP in J2EE. .NET?