Posts Tagged ‘aop’

Jonas Bonér, your regular AOP guy

February 4, 2006


Jonas is still standing when I meet him at the Öredev conference to discuss an interview. Even though a cold is doing its best to bring him to his knees. He still has a ‘roundthe-globe’ trip to Tokyo to do and the following sprint to reach JavaOne in Japan another one of those Swedes going places.

Jonas Bonér is the founder of AspectWerkz, an aspect oriented framework without the need for special compiler. It later joined forces with AspectJ, which could be described as the Father Christmas of aspect oriented programming in the Java world. He used to work for BEA in Sweden, but has recently joined Terracotta, San Francisco.

Jonas you’re a long term AOP advocate. When and how did you start with aspects and, perhaps most importantly, why?
I started using AspectJ back in 2001 and I was immediately very fascinated by the concepts of AOP, its power, beauty and ability to solve really hard problems in such an elegant way. I have always valued clean design and simplicity and in AOP I found a way of letting design and concepts map directly to actual code.
I started by using ‘policy enforcement aspects’, e.g. AspectJ’s declare error/warning, logging and tracing aspects, as part of the build process. After a while I gradually started to use it for more advanced things, such as security, transaction demarcation, persistence, caching, “unit of work”, design patterns etc. for better modularity, reusability, maintainability and simplicity.

Why did AspectWerkz and AspectJ merge?
The short answer is that the users needed a standard. But let me elaborate a little bit. During recent years the AOP landscape for Java has flourished. When a technology is new and immature it is usually a good thing to have many frameworks/products competing, since they can inspire and push each other and the technology even further, but when the technology matures it starts to become a problem. For example, the users might end up not knowing which framework, syntax and semantics to start using, since they do not know which ones will even be around a year later. If you see this happen a lot, like it did with AOP, then there is a need for standardization.
During 2004, AspectWerkz and AspectJ slowly converged, but the two projects were still focused on different areas and had complimentary strength. We had some discussions and both teams saw the need for standardization and felt that both projects as well as the user community would benefit from unifying the projects, roadmaps and teams instead of competing. So we decided on the merger that was announced in the beginning of 2005 and was completed with the release of AspectJ 5 at the end of last year.

So where do you think we’re heading for in the future, as far as AOP is concerned?
I am confident that AOP will play an important role in the future of enterprise application development. Many vendors are already starting to embrace AOP as an enabling technology for separation of concerns, transparency, simplicity etc. For example Terracotta DSO, JBoss EJB 3, TopLink, Spring etc.
These are all examples of vendors using AOP to layer infrastructure services on the user’s domain models in a transparent fashion. That is great, but I hope that it won’t stop with that, my wish is that users will see the value of using AOP in their application specific code, in order to achieve more modular design, code that is more easily written, understood, reused and maintained. In some ways AOP had a healthy backlash over the last year, which has removed most of the hype around it. It has matured, has a standard in AspectJ 5 and is ready for real-world deployments.

Tool wise it seems that we have several things in place in Eclipse/AspectJ/ AJDT to get a good grip on aspects. Examples: being able to see what code an aspect affects, diff engines to compare changes to an aspect etc. Do we have all we need?
The AJDT team has done a tremendous job and I think that we have already come a long way, even though more work can of course be done and needs to be done in this area. But while this is true for static views of the system, like AJDT is showing, there is almost no support for monitoring and introspecting the runtime view of the system, something that is getting more important now when the usage of dynamic AOP is becoming more widespread, which has the ability of redefining the behavior of the system at runtime. This is an area in which I hope that the academic community will contribute more in the future.

Can you see anything that needs to be fixed or added before we see more widespread adoption of AOP?
I think that the most important thing now is education trainings, books, articles etc. We need to try to reach beyond the group of “expert” developers. Another thing is a standard library. We need an ADK (Aspect Development Kit) in the same sense that Java has its JDK. I am involved in an attempt to gather and develop a set of library aspects for AspectJ 5, and we’ll see where that leads. Finally I hope to see more best-practices, patterns as well anti-patterns emerge.

Terracotta, the new company you work for, has a distributed cache product. What’s so cool about it?
It is completely transparent. Meaning that zero code changes are required to cluster an arbitrary J2EE application. Our only requirement is that you have to write a correct multi-threaded application. We then take that multi-threaded single VM application and a tiny bit of XML configuration to declaratively specify what should be shared, lock semantics etc., and turn it into a multithreaded multi-JVM application. These are the features I find most interesting:
* True transparency.
* Noserialization.We only send the actual changes to an object graph (the delta) as well as keep track of who is referencing who, so we can send these changes only to the nodes that need it, e.g. lazily.
* Object identity is preserved. We maintain Java’s “pass-by-reference” semantics, so regular object references work, which means that you can use your domain model the way you have designed it, as well as traditional OO design patterns etc. without a need to think about distribution, caching or clustering. • Coordination and memory manage-ment. We maintain the Java Memory Model transparently throughout the cluster, including distributed coordination, for example wait(), notify(), synchronized() etc., distributed garbage collection etc. We work as a virtual heap, meaning that you can for example run an application with 200G heap on a machine with 4G of RAM in which we then page in and out the heap on a demand basis.

How does it work?
We use AOP technologies to adapt the application at class load time. In this phase we extend the application in order to ensure that the semantics of Java are correctly maintained across the cluster, this includes object references, thread coordination, garbage collection etc. For example, we extend the semantics of a regular synchronized block, or actually maintain them across the cluster, by taking a global lock for the object instance that you are synchronizing on right before entering the block and releasing it right after exiting the block. You can declaratively define the exact semantics for the block, e.g. read, write, concurrent etc.
Another example is the invocation of notifyAll(). Here we turn this call into a cluster wide notification, which will open up for all nodes to contend for the lock.
The architecture is hub and spoke based, meaning that we have a central server which manages the clients, we use TCP/IP so the server just needs to be somewhere on the network. The client in this case is simply your regular application together with the Terracotta JAR. People always ask whether the server is not a single-point of failure, but we have a SAN-based solution to support fail-over in an active-passive manner. You can have an arbitrary number of (passive) servers waiting in line and upon failure the selected one will pick up right where the master server that has crashed left off.

Finally, as an active open source contributor, do you have anything up your sleeve for the future?
I have some ideas, but nothing I can talk about now. Stay tuned…

Something tells me that we will hear more from Jonas Bonér.
His cold? Well the trip actually made it go away. He made JavaOne with half an hour to spare. I guess it’s that Viking blood.

Originally published in JayView.

AOP featuring Rickard Öberg

February 2, 2004

I didn’t know what to expect, but the appearance of Rickard Öberg – a renowned programmer on the Java world scene – surprised me.
Apart from having written a book on RMI, he has been one of the core programmers behind JBoss. He instigated the XDoclet tool. WebWork, winning Java programming competitions, lectures and other achievements are also on his CV. Moreover, he’s not your average online personality, or perhaps he is? Anyone who remembers the Pet Store debacle*?

* Microsoft vs. Sun over the J2EE blueprint called PetStore. It resulted in a hot debate with many arguments.

I was sort of waiting to meet someone, well, far out. Instead this wholesome dude with a four-day beard greets me with a smile. I can’t help but to think of a strong caffe latte smooth milk blended with mind-altering caffeine.

Q: SiteVision is the content management system (CMS) sold by the company you work for, SenseLogic. Ok, without any prenuptial agreement, let’s get at the first question why?
Why do you use aspect oriented programming in SiteVision? After all, there isn’t that many product grade systems using aspects as a core design choice.

A: There are several reasons. When we began writing SiteVision we soon realized that we had to encapsulate reusable code in a number of places, especially features that were side effects of method calls. Object had to be saved on setter calls, events had to be sent, logging had to be done, transactions should be managed, and so on. We couldn’t figure out a way to do it using standard technology, e.g. EJB, so the only solution was to use AOP.

We were also on a very tight schedule. In just a couple of months we had to build a commercially viable CMS-tool using only five developers, and after that we had to maintain and develop it at such a rate as to catch up, and pass, our competition. It really should be impossible, and it would be with standard technology. The solution was to avoid writing code by using AOP. AOP allows an extreme degree of reuse of code, and because of this we managed to write lots of features with a minimal effort, and since we avoided writing unnecessary code to a large extent it also became easier to maintain. In addition, since AOP makes it easy to add functionality incrementally we were also able to enhance the architecture and implementation as we went along without having to change much of what was already written.

Q: Why roll your own aspect engine? Why didn’t you decide to use AspectJ or some other aspect-inspired tool?
A: After the decision to use AOP was made I researched the available tools on the market, and compared their feature sets with our requirements, especially with regard to code maintenance, performance, scalability. None of the tools, including AspectJ, had been written with such requirements in mind, so we had no alternative but to write our own tools. My background in EJB made it possible for me to combine the principles of AOP with our requirements in a good way.

In hindsight I can conclude that it was the right decision, and if I were to make the same decision today I would still do the same. There is, in my opinion, still a lack of good AOP-tools that support the demands of a complex server side application. The awareness of the importance of such tools is on the increase however, so I would be surprised if this has not changed by next year.

Q: AOP being a true paradigm shift what are the biggest changes when going aspect?
A: There are two things that stand out, from a design and implementation point of view. First of all it takes some time to learn to recognize “cross-cuttting concerns”, that is, code that can be extracted into an aspect. Second, the use of static introductions as a design tool gives one a whole new set of posssibilities with regard to domain model design. Instead of using inheritance as the main building block for reuse of code one would use design by composition, which gives you many more possibilities for combining existing components. It takes a while to get used to this new freedom, but once you do that everything is fine.

Q: SiteVision is soon to go version 2. Has your view on AOP changed during the trip?
A: In the beginning I was, as most others seem to be now, fascinated with the concept of interception. What difffers now, almost two years later, is partly a realization of the importance of static introduction, and partly the understanding of how important it is to have a powerful pointcut model. AOP has so much more to offer than just method call side effects.

As for AOP in general it is great to see that more developers are beginnning to see the advantages of it, even though the examples often are so trivial that it’s hard to see the point of it. I’m also waiting for more people to realize just how powerful static introductions are as a design tool, and the consequences this has for design pattterns and such issues.
It’s going to be quite a revolution, and several tools that exist today in order to avoid the problems of current system design techniques are going to get a tough time.

Q: Do you dare to mention tools, or types, that will have problems?
A: I suppose XDoclet is the most obvious one. We are not using any code generation at all in SiteVision, and that is solely because we have been able to avoid all the problem of standard design principles by using AOP.

Q: Let’s pull out the tarot cards. What’s in the future for AOP?
A: The theoretical part of AOP seems to be stabilizing, but we will probably see more tools in the AOP space. Some people ask, “Why not only use AspectJ?” but I think that’s like saying, “Why not just drive BMW?”. There’s nothing wrong with a BMW, but sometimes a Volkswagen works better, and sometimes a Porsche is the only choice.
As usual it’s about choosing the tool that best matches your requirements, and I can’t see AspectJ being able to match all different kinds of requirements at the same time.

Apart from the AOP frameworks it will also be very important to have good support tools, especially with regard to visualization of AOP systems. Since AOP to a large extent is about fragmentizing and componentizing code it can sometimes be difficult to see what a component does just by reading code. A visualization tool for AOP can put together all the different pieces that make up the whole, and present them as one unit even though they have been developed separately. Access to this kind of tools is, of course, crucial.

We have built such a tool ourselves for our own system, and it has been very helpful when we are expanding the system and when we are looking for bugs.
The step after that, I guess, is the possibility to build packaged aspects that can be reusable in your own projects. However, predicting component markets have proven to be a notoriously difficult task so I’m not going to bet on it.

Q: …and the future for SiteVision?
A: Without revealing too much we can see that our framework and way of building systems gives us interesting opportunities to build application using AOP which run in SiteVision as portlets. Our next version expands the product into the portal segment, and the next logical step after that is to include document management features. We are also looking into how to provide scalability through clustering, and have some rather unique ideas there. But, one thing at a time.

Q: For the finale What are your top five advices for the wannabe aspect programmer?
A:

  1. Read “Design Patterns” (the GoFbook)
  2. Read the documentation for AspectJ
  3. Find a medium size example application and implement it fully using AOP. Pick the framework which best suits your needs. I would start looking at AspectJ for client side development and AspectWerkz for the server side.
  4. Apply design patterns using AOP as far as possible.
  5. Read the AOP-entries in my blog 🙂

It is somewhere around here, at the end of the interview, that I start to long for a good cup of coffee, some Java and lots of aspects 🙂

Resources
SenseLogic: http:// www.senselogic.se
Rickard's blog: http://www.jroller.com/page/rickard

Originally published in JayView.

Ytterligare en Aspekt på din kod

January 20, 2004

Har du någonsin kopierat vissa snuttar kod – om, om och om igen? Trots att du redan har en snygg objektorienterad arkitektur? Trots att den är full med de bästa design-mönster som går att uppbringa? Trots att du valt de bästa verktygen och ramverken? Lika förbaskat så sitter vissa rader, som loggning, både i ryggraden och i varje klass. Vad är fel? Och hur kan man undvika det? Aspektorienterad programmering (AOP) kan vara svaret – om inte annat så är det ett paradigmskifte värt några hjärnceller.

Trots att vi anstränger oss till det yttersta att modellera våra system intill perfektion, nåja i alla fall väldigt, väldigt nära, så är det fortfarande svårt att fånga strukturen hos ett problemområde. Detta märks t ex genom att vi kopierar välbehövliga små bitar kod och lägger in dem överallt. Inte nog med detta, de klasser som helst bara skulle behöva lösa en uppgift, tvingas att känna till säkerhet, databas, loggning osv. Allt detta leder till system som är svåra att underhålla och förändra.

Vad skulle hända om vi kunde plocka ut all loggning i våra projekt och lägga dem i en separat klass – en aspekt? Istället för att sprida ut en viss lösning i vårt system, kan vi nu underhålla den på ett enda ställe. När programmet kompileras så förs koden tillbaks ut där vi hade den innan.

För att bättre förstå vad aspekter är tittar vi närmare på AspectJ, som är en variant av AOP baserad på öppen källkod. Den har flera år på nacken och skapades på Xerox PARC som ett forskningsprojekt med stöd av DARPA.

Ett exempel: Var finns egentligen koden för loggning?

En vanlig syn är loggningen som ligger utspridd över ett helt system. När vi inför en aspekt så får vi ett enda ställe att underhålla den på.

Kodpunkt, punktsnitt och direktiv

I aspektorienterad programmering kan man samla alla dessa små bitar kod på ett enda ställe. Men vi måste ju fortfarande kunna köra dessa på givna ställlen i programmet? Lösningen i AspectJ är att identifiera punkter i exekveringen av ett program – så kalllade kodpunkter (joinpoints).
Det finns flera olika typer av kodpunkter man kan identifiera; metodanrop, skapande av objekt, att sätta attribut, utlösning av undantag (exceptions) osv. Ett punktsnitt samlar en omgång kodpunkter och ger dem ett namn.
Genom att ange kod, direktiv (advice), som ska köras vid dessa kodpunkter kan vi samla tvärgående intressen (crosscutting concerns) i en enda fil – en aspekt. Eller annorlunda uttryckt:

aspekt = punktsnitt(kodpunkter) + direktiv

En aspekt består av en omgång identifierbara punkter i programmet där extra kod ska köras.

Vad kan man göra mer?

Vi har bara gått igenom ett hyfsat enkelt exempel till höger, men det finns många saker man kan använda AspectJ:

  • Olika former av loggning och debugging.
  • Design-by-contract, d v s att man kollar inoch utgående tillstånd och parametrar. När man är nöjd att systemet uppfyller kraven kan man ta bort dessa aspekter.
  • Testa optimering, alternativa lösningar etc.
  • Cachning, synkronisering, accesskontroll etc.
  • … och fler tekniska aspekter som inte har med vårt problemområde att göra.

Innan har vi endast talat om dynamisk förändring av ett program, d v s att påverka arbetsflödet. Men det går också att ändra den statiska strukturen genom att lägga till t ex klassvariabler, metoder, ändra arv. Här uppstår fler möjligheter:

  • Multipelt arv som t ex mix-in i C++
  • Genomförande av kodstandard. ”Ingen får ändra en variabel direkt”. Denna koll kan t o m göras vid kompilering!

Listan kan göras mycket längre. Vi befinner oss bara i början av vår förståelse om var och hur vi bäst använder aspektorienterad programmering. Även om denna inte kommer att ersätta objektorienterad programmering (OOP) så kommer den att vara grunden för AOP på samma sätt som funktioner utgör grunden för OOP.

Ett enkelt (nåja) exempel

Vi skulle kunna gå igenom ett enkelt ”Hello Aspect World”, men jag väljer iställlet att dyka i lite djupare. Jag vill mäta hur lång tid det tar att anropa databasen i vårt hemmasnickrade modelllager.
Vår modellkod innehålller en abstrakt klass som definierar ett gränssnitt för att arbeta mot databasen. Personklassen representerar en post i person-tabellen och implementerar själva anropen med SQL mot databasen i metoderna dbSave, dbUpdate och dbRemove. I ett anfall av hybris lägger jag in mig själv i databasen. Demokod:

Vårt enkla modell-lager som kapslar in databasen.

DBObject tPerson = new Person();
tPerson.setField("firstName", "Björn");
tPerson.setField("lastName", "Granvik");
tPerson.dbSave();

tPerson.setField("company", "Jayway");
 tPerson.dbUpdate();

Du gamla vanliga lösning

Låt oss nu göra en enkel tidtagning. På det gamla sättet så blir det till att kopieraoch-klistra, så mycket som vi nu orkar. Till exempel skulle Person.dbSave kunna se ut som följer:

void dbSave() {
    long tTime = System.currentTimeMillis();
    // Do something...
    tTime = System.currentTimeMillis() tTime;
    System.out.println( thisJoinPoint + ": " + tTime );
}

Och på samma sätt för de andra metoderna dbUpdate och dbRemove. Även om vi förbättrar situationen genom att introducera en tidtagningsklass blir det bara marginellt bättre – det är fortfarande korkad kod! Dessutom så kommer den att ta tid att exekvera. Inget vi vill ha kvar i en produktionsversion.

Du sköna nya aspekt

Låt oss titta på hur man skulle kunna lösa problemet med hjälp av aspekter. Vår nya lösning innehåller en del nya ord som tillägg till Java-språket, se fetstil nedan, men är inte så svår som det först verkar.

/* A timing aspect on DBObject.db methods */
public aspect DbTimerAspect {

    /* Public DBObject methods starting with 'db',
     * taking no parameters and returning anything. */
    pointcut dbMethods() : execution( public * DBObject.db*());

    /* A simple timer advice to be called instead
     * of the original method. */
    void around() : dbMethods() {
        long tTime = System.currentTimeMillis();
        proceed();    // Proceed with call to DbObject.
        tTime = System.currentTimeMillis() tTime;
        System.out.println( thisJoinPoint + ": " + tTime );
    }
}

Vår aspekt DbTimerAspect innehåller dels de metoder som vi vill mäta och den tidmätare vi vill ska köras.
I kodsnittet dbMethods (pointcut) väljs de publika metoder i DBObject och dess subklasser som börjar på ”db”. Vi anger också att det är när metoden körs (execution) som är intressant. Här kan man välja på fler varianter; när metoden anropas, när ett attribut ändras, när ett objekt skapas och många fler sorters kodpunkter.

När demokoden anropar Person.dbSave så är det vårt direktiv som körs istället. Nyckelordet som anger detta är around. Vi hade naturligtvis kunnat ange att den skulle köras före, efter osv. Det första vi gör är att ta reda på tiden. I nästa steg anropar vi originalmetoden med ”proceed”. Nu körs Person.dbSave som vanligt.

Efter att vi kommer tillbaka räknar vi ut den tid som tillbringats i anropet och skriver ut den på konsolen. Lägg märke till att vi har tillgång till den kodpunkt som vi befinner oss i m h a thisJoinPoint. Resultat
När vi kompilerar vår kod gör vi det med kompilatorn från AspectJ. Den genererar ren Java ”byte code”, dvs. koden kan köras precis som vanligt.

Resultatet på konsolen blir:

execution(void se.jayway.jayview.aop.Person.dbSave()): 111
execution(void se.jayway.jayview.aop.Person.dbUpdate()): 30

Ganska mycket det vi förväntade oss.

Slutkläm

Denna artikel räcker egentligen inte för att förstå hela vidden av det man kan göra med aspekter. Jämför vi med en vinprovning har vi bara hunnit titta på etiketten. Men, likväl, vårt lilla exempel pekar på de stora möjligheter som finns med aspekter.
När och var bör man då använda AOP? Än så länge är aspekter inte ”bevisade”. Hur kommer de att skala? Hur påverkas arkitekturen i skarpt läge etc?
Däremot så är det mycket intresssant att förbättra hur vi utvecklar dessa system. Mitt råd blir därför; Skapa aspekter som stödjer din kodstandard, testar varianter av din lösning utan att behöva modifiera koden, gör verktyg som t ex loggningsaspekter, etc.
Om jag ska våga mig på en gissning tror jag att vi inom några år kommer att ha sådana ”tekniska” aspekter som öppen källkod. Fast jag kan ha fel – de kommer kanske redan om ett år eller så 🙂

Termer

kodpunkt (joinpoint) En punkt i exekveringen av ett program, till exempel i anropet av en metod i en klass.
punktsnitt (pointcut) En samling utvalda kodpunkter.
direktiv (advice) Kod som körs vid utvalt punktsnitt under angivna omständigheter, t ex kan man logga ett anrop innan det körs.
tvärgående intressen (crosscutting concerns) Ett system har oftast flera mål som det försöker uppfylla. Förutom att lösa grundproblemet (t ex lönehantering) så finns där också uppgifter som t ex loggning, säkerhet etc. Dessa uppgifter, eller intressen, är typiskt utspridda i systemet – de går på tvären genom strukturen.
OOP Objektorienterad programmering en programmeringsteknik och synsätt som gör det möjligt att öka komplexitetsgrad och återanvändning.
AOP Aspektorienterad programmering att göra fristående moduler som hanterar tvärgående intressen på ett sådant sätt att de kan sömlöst kan föras in i koden igen vid t ex kompilering.

Resurser
AspectJ
Eclipse, AspectJ plug in
JavaWorld: I want my AOP!
AOSD – Aspect Oriented Software Development

Originally published in JayView.