Archive | March, 2009

Powerful combination: JMX + Annotation + AOP

What is AOP?

AOP is a way to modularize cross-cutting concerns. Ok, what does “modularize” really mean? Modularization is the encapsulation of a unit of functionality. It is exactly what “Class” is doing in OO world. How about “cross-cutting concerns”? Basically it means any functionalities that span multiple modules/ classes. They include Transaction Management, Security, Caching, Performance Monitoring and etc. To understand how AOP works, we first look at the common terms in this area:

  1. Join point – An identifiable point in the execution of a program like method invocation, exception thrown.
  2. Pointcut – Program construct that selects join points and collects context at those points. AspectJ has a rich pointcut expression language!
  3. Advice – Code to be executed at a join point that has been selected by a pointcut.

To me, I found it easier to understand these terms if I consider join point as event generated point in code, pointcut as a way to define what events to be captured and advice as event handler.

AOP is indeed a powerful way to factor out system or infrasturcture-related code from the business oriented code. Typically, we use it to take care of transaction, security and profiling aspects. But it doesn’t stop you putting creativity in this domain. With a bit more creativity, you can also do the following::

  1. Exception translation – checked to runtime
  2. Catch ConcurrencyFailureExceptions and transparently retry if an idempotent operation fails with, for example, a deadlock loser exception.

How I use Spring AOP in my project?

I have been told to report the elapsed time for all calls to the database. If I don’t know how to use AOP, I may end up putting code to measure time for every JDBC calls. It ends up tangling performance monitoring code with my main line business logic and the same logic will be scattered everywhere in my data access code. Bad!! That is why we need to know how to factor out the performance monitoring code into an aspect like below:

Here we use AspectJ annotation approach to implement the aspect. “Around” is to intercept start and end of any repository method. Here is what states in Spring 2.5 reference:

Spring 2.0 introduces a simpler and more powerful way of writing custom aspects using either a schema-based approach or the @AspectJ annotation style. Both of these styles offer fully typed advice and use of the AspectJ pointcut language, while still using Spring AOP for weaving.

If you use AspectJ annotation, you need to put <aop:aspectj-autoproxy/> in your application-context.xml. The limitation of Spring proxy-based AOP is that it is limited to method invocation interception. To get around that, you can use AspectJ syntax in your pointcut expression. You don’t need to build the application with ajc (the AspectJ compiler) even you are using AspectJ syntax. Spring AOP can also understand @AspectJ aspects. I strong suggest you use Annotation driven AOP because it is cleaner and simplier. Working with AOP, I have faced 2 questions.

  1. How to select the methods that I want to intercept without hardcoding the method or package name in my pointcut expression. So, my aspect or pointcut doesn’t contain application specific information – Look into annotation and AOP section.
  2. How to turn on and off AOP without restarting the web application? I would use JMX. Look into “What is JMX” section. 

Annotation and AOP

Annotation provides a better way other than code signature for selecting join point that leads to creating loosely coupled aspect. In fact, you can see annotation as another signature of a method in other dimension. And a method can have multiple annotations and each concern just bother its own annotation. It is called multidimensional signature space. For example,

@Authentication(“bankOperation”)
@Transactional(REQUIRED)
public void credit(){…}

Pointcut uses annotation to capture join points. For example:

execution(@Transactional * *.*(..)) Execution of a method annotated as Transactional
execution((@Trasactional *) *.*(..)) Execution of a method that returns object annotated as Transactional
execution(* (@Transactional *).*(..)) Execution of a method defined for type annotated as Transactional

Selection can use Annotation types and Annotation values.  What is more, annotation values can be used in Advice implementation.

Here is a great video from Parleys that talked about “Leveraging Annotation with AOP”. I have included some key points Ramnivas made here:

  • Write you pointcut in a smart way to avoid annotation mess. Try to use naming and package convention to help you. For example, if you want to write app log for all public facing service method, you can use “public” with package name containing “service” wildcard to help you.
  • If you really need to use annotation like @Transaction that designer has no way to define the pointcut beforehand, use annotation to describe what the join point is but not how to handle it. So, your transaction aspect only need to worry annotation @Transaction and decouple from the application.
  • You can piggyback annotation. For example, you can make all entities auditable via declare @type: @Entity *: @Auditable; 

How does Spring AOP work internally?

The magic behind AOP is the concept of Proxy/ Decorator/ Interceptor/ Filter pattern. To me, all those patterns are conceptually the same. They all try to present itself as target object (thru implementing the same interface), intercept method call and execute injected logics. And you can have more than one interceptors invoked in series. In Spring AOP, there is one thing we need to pay attention:

However, once the call has finally reached the target object, …any method calls that it may make on itself, such as this.bar() or this.foo(), are going to be invoked against the this reference, and not the proxy. This has important implications. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute. To handle this, either you refactor your code such that the self-invocation does not happen (best approach) or you make self invocation call thru proxy like ((Pojo) AopContext.currentProxy()).bar() (invasive approach b/c it totally couples your code to Spring AOP, and it makes the class itself aware of the fact that it is being used in an AOP context, which flies in the face of AOP. Avoid using it).

However, it must be noted that AspectJ does not have this self-invocation issue because it is not a proxy-based AOP framework.

What is JMX?

In short, it is a way to enable management and monitoring of Java applications over a generic API. JMX has a simple architecture that contains instrumentation level, agent level and distribution service level. In instrumentation layer, we register MBean to the MBeanServer. In simple term, In simple term, MBean is a  JavaBean with defined management interface that exposes attributes and operations to the world. MBeanServer acts as a broker to decouple communication among application MBeans and/or remote clients.

Combine AOP and JMX

AOP is statically defined and intercept at the runtime. It is hard to take this out or add another aspect in after you start your machine. However, with JMX, you can enable and disable it via skipping the aspect code. :cool: On the other hand, you can also use JMX to configure and report SLA metrics like configure thresholds and send notifications of violations. That sounds very interesting to me. There are other interesting usages mentioned in the Parley’s video as well:

  1. Service blocking – throw an exception if particular service you don’t want to user to use it for a period of time esp during maintenance time.
  2. Caching management – I am currently using interceptor pattern and IoC to intercept dao method calls for cache lookup. 

Reference

  1. JavaOne 07 – JMX, AOP and Spring (Nice Presentation)
  2. Parley’s AOP and JMX (Video)
  3. Simplifying Enterprise Applications with Spring 2.0 and AspectJ
  4. Workflow Orchestration Using AOP
  5. Performance Monitoring with AOP and JMX

 

Leave a comment Continue Reading →

Flex Startup Sequence

Magic behind the scene

I always wonder how my Flex application displayed on the Flash Player in browser. Why decompile Flex SWF will give me 2 frames movie? What is SystemManager and how can I get a handle of it? Many of these kind of questions are at the lower level. The level that makes Flex application possible. Normally, we don’t need to dive into this to write a Flex application. However, it would make me feel more comfortable to understand this before I advocate Flex as the main part of our company’s UI strategy. 

To understand how your Flex application got loaded and display on Flash Player, you can read this great article. I am going to put down the sequences in steps below:

Flex is a 2-frame movie

The first frame of a Flex SWF contains the SystemManager, the Preloader, the DownloadProgressBar and some glue helper classes. Remember, the Preloader is what creates the DownloadProgressBar control which displays the progress of a Flex application downloading and being initialized. The second frame of a Flex SWF contains the rest of the Flex framework code, your application code and all of your application assets like embedded fonts, images, etc.


By creating a 2-frame movie, Flex applications can take advantage of the streaming support built into the Flash Player and a preloader can appear before all of the Flex framework code and your application code are downloaded.

The .swf format is a progressive download format which means that Flash player can access content on frames as they download without having to wait for the entire file to download.

Here are the steps:

  1. First, enough bytes for frame 1 are streamed down to the Flash Player.
  2. The Flash Player executes those bytes by creating a SystemManager instance.
  3. SystemManager instruct the Flash Player to stop at the end of frame 1.
  4. SystemManager then goes on to create the Preloader which creates the DownloadProgressBar control and pops that up on the client screen.
  5. The Preloader then starts tracking the rest of the bytes streaming in from the Flex SWF. 
  6. Once all the bytes for the Flex framework and application code are in, the System Manager goes on to frame 2 and instantiates the Application instance.
  7. Once the Application instance has been created, the SystemManager sets Application.systemManager to itself. This is how you, the application developer, can access the SystemManager at a later time.
  8. The Application dispatches the preinitialize event at the beginning of the initialization process.
  9. Application goes on to create its children. The method createChildren() is called on the application. At this point each of the application’s components is being constructed, and each component’s createChildren() will be also called. For detail, look at component lifecycle section.
  10. The Application dispatches the initialize event, which indicates that all application’s components have been initialized. However, at this state, all the components are not yet laid out.
  11. Eventually, once all the Application child controls and containers have been created, sized and positioned, the Application dispatches the creationComplete event.
  12. Once the creationComplete event has been dispatched, the Preloader removes the DownloadProgressBar control and the SystemManager adds the Application instance to the Flash Player display list. (The Flash Player display list is basically the tree of visible or potentially visible objects that make up your application. When you add and remove child components to your application, your basically just adding and removing them from the display list).
  13. Once the Application is added to the Flash Player display list, the Application dispatches its applicationComplete event
  14. The Application has been created and is up on the screen ready to be interacted with.
     

Component Architecture

 This is the best video I have found that discuss the component lifecycle in detail – Thanks for Deepa.

Below is summary I took from the video above, in case you don’t want to spend an hour to listen to this. However, I really think you should. To start out, Deepa introduced component and skinning architecture “Spark” that is part of Flex 4 Gumbo. Spark is built on top of Halo (ie. Flex 3 component architecture) and components using Halo or Spark can co-exist. Then,  Deepa put her focus to talk about how to develop her custom video component on top of Halo and Spark for comparison. Spart is great that it can factor out the layout code from component.

Halo component lifecycle can be separated into 3 phases:

Phase 1 – Initialization

  1. Construction
    • Choose the right base class and provide default constructor (ie. zero argument). By extending UIComponent, you inherit all of the lifecycle methods, events and properties. Also, since UIComponent extends from EventDispatcher, your component inherits the ability to listen and dispatch events.
    • Best practice: Call super() and add event listener. Minimal work should occur here.
  2. COnfiguration
    • setter and getter for properties.
    • Involve in invalidation and validation cycle. Detail later.
    • Best practice: Setter should not expect the internal children have been created and you want your setter to be fast. Use _xxx for storage variable and have dirty flag for your variable. Throw events out when the internal state of your component get changed.
  3. Attachment
    • Component are added to the flash display list by its parent via addChild() call. Without attachment, component lifecycle will be stalled. Nothing is going to happen to your component. So, this is an important step.
    • Display list is a tree of visible or potentially visible objects in your application. At the root of the display list is your main application. Thing like containment hierarchy and rendering order are all maintained by the display list.
  4. Initialization- 5 lifecycle actions occur here.
    • preinitialize event is dispatched. It signifies that you as component that has been added to the display list by your parent via addChild().
    • createChildren() – walk through all your children, create, configure and attach them to the display list. Best practice: Call super.createChildren(), construct if not exist and attach your children via addChild(). If your child component is dynamic and data driven, use commitProperties() b/c it gets called at every invalidation and validation cycle. Halo rules: Container –> nested structure of UIComponents –> MovieClip, Video, Shape and Sprite.
    • initialize event is dispatched. It signifies that you and all your children are created and attached.
    • First invalidation/ validation pass occurs,
    • creationComplete event is dispatched. Ready for prime time.

Phase 2 – Update

At this phase, your component is fully initialized and ready for usage. Now, it needs to know how to update. And update occurs when its internal state has been changed by like user interactions. To respond to the changes, component uses the invalidation and validation cycle. The key here is to flag the changed variable dirty during invalidation and later handles it during validation right before rendering. So, you can have many invalidation and one validation that gives better performance via avoiding repetitive work. To better understand this approach, Deepa talks about Flash Player Elastic Racetrack that has 2 parts: code execution and rendering. If either part taking too long, Flash player cannot get its job done faster than 1 frame per second. You will see your application with lag and halt, that is bad! 

  1. Invalidation/ Validation can be split into 3 phase.
    • InvalidateProperties –> commitProperties
    • InvalidateSize –> measure (measure may not be called. Don’t have your code depends on it)
    • InvalidateDisplayLIst –> updateDisplayList

Phase 3 – Destruction

  1. Detachment
  2. Garbage Collection

 

What is Mixin?

When you put the [Mixin] metadata just above your class definition and add a static init function to the class like so,

[Mixin]
public class Model {   
  public static function init (systemManager : ISystemManager)   {     
    trace ("I get called first")   
  } 
}

The static init function will be called as soon as your application loads (assuming this class is referenced somewhere in the app), much like static initialization blocks in Java. This is useful if you have some code that you want to run before any of the other code in the class.

Reference

Below are some interesting articles I found related to this article

  1. Create Custom Preloader, Ted has an article related to this too
  2. Speed up startup loading time
  3. Dynamic loading a new custom theme without fraction seconds delay
  4. Deepa presentation in MAX
  5. Introduction to mixins

 

Leave a comment Continue Reading →