<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Cake Solutions Team Blog &#187; AOP</title>
	<atom:link href="http://www.cakesolutions.net/teamblogs/tag/aop/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cakesolutions.net/teamblogs</link>
	<description>void magic() { }</description>
	<lastBuildDate>Tue, 07 Feb 2012 12:02:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Scala and AspectJ</title>
		<link>http://www.cakesolutions.net/teamblogs/2011/11/07/scala-and-aspectj/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scala-and-aspectj</link>
		<comments>http://www.cakesolutions.net/teamblogs/2011/11/07/scala-and-aspectj/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 11:27:21 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[AOP in Scala]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Scalad]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1110</guid>
		<description><![CDATA[I like Spring Framework&#8216;s transactional support, especially the transactional aspects. The aspects, in combination with various implementations of the PlatformTransactionManagers and AspectJ&#8217;s load-time weaving let me use declarative transaction management. So, in Spring, I can have @Service @Transactional public class &#8230; <a href="http://www.cakesolutions.net/teamblogs/2011/11/07/scala-and-aspectj/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I like <a href="http://www.springframework.org" target="_blank">Spring Framework</a>&#8216;s transactional support, especially the transactional aspects. The aspects, in combination with various implementations of the <code>PlatformTransactionManager</code>s and AspectJ&#8217;s load-time weaving let me use <em>declarative</em> transaction management. So, in Spring, I can have</p>
<pre class="brush:[java]">@Service
@Transactional
public class SomeService {

    public void work() {
        // perform all operations here with
        // transactional semantics
    }
}
</pre>
<p>Combine the lightweight <code>@Transactional</code> annotation with <code>&lt;tx:annotation-driven mode="aspectj"&nbsp;/&gt;</code> and AspectJ&#8217;s load-time weaving and <code>&lt;context:load-time-weaver&nbsp;/&gt;</code> or compile-time weaving (typically in your <code>pom.xml</code>), and you&#8217;re done.<br />
I wanted to include something similar in <a href="http://www.cakesolutions.org/scalad.html">Scalad</a>. The &#8220;trouble&#8221; is that I did not want to include any dependency on the Spring Framework (though I wanted to be able to use the Scalad code in Spring, if necessary); I wanted to be able to declare that all methods in a class are transactional; and I didn&#8217;t want to write unnecessary code.</p>
<h3>Scalad.transactionally</h3>
<p>The core of the operation is the <code>transactionally</code> method that applies the transactional semantics to some function <code>f</code>:</p>
<pre class="brush:[scala]">
def transactionally[A](manager: PlatformTransactionManager)(f: =&gt; A) = {
  val transaction = manager.getTransaction
  try {
    transaction.begin()
    val ret = f
    transaction.commit()

    ret
  } catch {
    case e: Exception =&gt;
      transaction.rollback()
      throw e
  }
}
</pre>
<p>That&#8217;s the transactional logic and we can use it in our Scala code:</p>
<pre class="brush:[scala]">
def foo = {
  transactionally(somePlatformTransactionManager) {
    // executes with transactional semantics
    "42"
  }
}
</pre>
<p>The problem with this code (at least for me) is that it is easy to forget; if I had a class where every method were transactional, then I&#8217;d have a lot of repeated code on my hands.</p>
<h3>Transactional trait and TransactionalAspect class</h3>
<p>A solution to my laziness is the <code>TransactionalAspect</code>, which contains (amongst others) the transactional advice that is applied <em>around</em> applicable methods. </p>
<pre class="brush:[scala]">@Aspect
class TransactionalAspect {

  @Pointcut("execution(* *(..))")
  private def anyExecution() {}

  @Around(value = "anyExecution()")
  def transactionally(pjp: ProceedingJoinPoint) = {
    val platformTransactionManager = ???
    Scalad.transactionally(platformTransactionManager) {
      pjp.proceed()
    }
  }

}
</pre>
<p>This feels almost right: I can intercept methods and apply the transactional semantics to them. But what about the <code>PlatformTransactionManager</code>? Where should I get that object from? In Spring, life was easy: I had a well-known <code>ApplicationContext</code> and I could look up the bean that implements the <code>PlatformTransactionManager</code> interface. In Scalad, there may not be any such <code>ApplicationContext</code>.<br />
Instead, I take a slightly different approach. If I want to apply the transactional semantics to methods in a class, I need to mix-in the <code>Transactions</code> trait; the trait contains a single abstract method <code>getPlatformTransactionManager</code>. This method is implemented in the various concrete data access classes (for example, in <code>JPA</code>), but none of the concrete data access classes mix-in the trait:</p>
<pre class="brush:[scala]">class JPA(private val entityManager: EntityManager) {
  require(entityManager != null, "The 'entityManager' must not be null.")

  import Scalad._
  import scalaz._

  def getPlatformTransactionManager =
    new JPAPlatformTransactionManager(entityManager)

  ...
</pre>
<p>So, you can decide whether you want [automatic] transactions or not:</p>
<pre class="brush:[scala]">
class Worker(entityManger: EntityManager) extends JPA(entityManager) {
  def work = …
  def somethingElse = …
}
</pre>
<p>or</p>
<pre class="brush:[scala]">
class Worker(entityManger: EntityManager) extends JPA(entityManager)
  with Transactions {

  def work = …
  def somethingElse = …
}
</pre>
<p>The <code>Transactions</code> trait gives me access to the <code>PlatformTransactionManager</code> in the advice:</p>
<pre class="brush:[scala]">@Aspect
class TransactionalAspect {

  @Pointcut("execution(* *(..))")
  private def anyExecution() {}

  @Pointcut("this(transactional)")
  private def transactionalTrait(transactional: Transactions) {}

  @Around(value = "anyExecution() &#038;&#038; transactionalTrait(transactional)")
  def transactionally(pjp: ProceedingJoinPoint, transactional: Transactions) =
    Scalad.transactionally(transactional.getPlatformTransactionManager) {
      pjp.proceed()
    }

}
</pre>
<p>The <code>transactionally</code> advice now receives the <code>ProceedingJoinPoint</code>, allowing me to proceed to execute the unadvised target, but also the <code>Transactions</code> trait&#8211;the object on which the advised methods are being executed.</p>
<h3>Weaving</h3>
<p>Weaving is a process where AspectJ modifies the bytecode of the advised methods with the advices: and so, the only time this can happen is when an advised class is being compiled is being loaded into the JVM&#8217;s memory. Compile-time weaving is easy to understand: we first compile our code (using any compiler that prodoces Java bytecode) and then we use the AspectJ weaver to modify the already procuded bytecode.<br />
Load-time weaving is sligtly more complex: We need to be able to hijack&#8211;<em>instrument</em>&#8211;the JVM&#8217;s class loading process. We use the Java Agent in the JVM. All we need to do is to set the <code>-javaagent:/path-to/aspectjweaver.jar</code> JVM parameter.<br />
The AspectJ&#8217;s Agent will then find all <code>META-INF/aop.xml</code> files and use the information to drive the weaving process. (The same weaving process that is executed during the compile-time weaving.) In Scalad&#8217;s code, the <code>aop.xml</code> references the <code>TransactionalAspect</code>:</p>
<pre class="brush:[xml]">
&lt;!DOCTYPE aspectj PUBLIC
    "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"&gt;

&lt;aspectj&gt;

    &lt;weaver options="-verbose"/&gt;

    &lt;aspects&gt;
        &lt;aspect name="scalad.transaction.TransactionalAspect"/&gt;

        &lt;include within="*"/&gt;
        &lt;exclude within="javax.*"/&gt;
        &lt;exclude within="org.aspectj.*"/&gt;
        &lt;exclude within="scala.*"/&gt;
        &lt;exclude within="scalaz.*"/&gt;
        &lt;exclude within="scalad.*"/&gt;
    &lt;/aspects&gt;

&lt;/aspectj&gt;
</pre>
<h3>Running</h3>
<p>We will run the example application with AspectJ&#8217;s load-time weaving. All that is required is to include the <code>-javaagent</code> JVM parameter when running the <code>Main</code> class. You will find the weaver JAR in your Maven repository in <code>~/.m2/repository/org/aspectj/aspectjweaver/1.6.11/aspectjweaver-1.6.11.jar</code>.<br />
<a href="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/11/scaladrun.png"><img src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/11/scaladrun-300x231.png" alt="" title="scaladrun" width="300" height="231" class="aligncenter size-medium wp-image-1122" /></a></p>
<h3>Code</h3>
<p>As usual, the code is at <a href="https://github.com/janm399/scaladata">https://github.com/janm399/scaladata</a> and more details are at <a href="http://www.cakesolutions.org/scalad.html">http://www.cakesolutions.org/scalad.html</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2011/11/07/scala-and-aspectj/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sub-millisecond Java</title>
		<link>http://www.cakesolutions.net/teamblogs/2008/11/19/sub-millisecond-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sub-millisecond-java</link>
		<comments>http://www.cakesolutions.net/teamblogs/2008/11/19/sub-millisecond-java/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 15:56:34 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[High Performance Java]]></category>
		<category><![CDATA[RDTSC]]></category>
		<category><![CDATA[real-time Java]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=94</guid>
		<description><![CDATA[Imagine you had to implement (complex) code in Java that runs in sub-millisecond time. How will you know that you&#8217;ve succeeded? The traditional measurement such as this one won&#8217;t work. long before = System.currentTimeMillis(); doSomeWork(); long elapsed = System.currentTimeMillis() - &#8230; <a href="http://www.cakesolutions.net/teamblogs/2008/11/19/sub-millisecond-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Imagine you had to implement (complex) code in Java that runs in sub-millisecond time. How will you know that you&#8217;ve succeeded? The traditional measurement such as this one won&#8217;t work.</p>
<pre><code>
long before = System.currentTimeMillis();
doSomeWork();
long elapsed = System.currentTimeMillis() - before;
// check that elapsed < 1
</code></code></pre>
<p>This is not great. It turns out that the operating system&#8217;s tick measurement greatly depends on the platform. On the Intel platform, the OS uses the default timer, which ticks 128 times a second. That means that the timer resolution will be roughly 8 ms. <i>Not great</i>. We need something far more accurate.<br />
It turns out that on Intel CPUs (Pentium and above), you can use the <code>RDTSC</code> instruction that returns the number of processor ticks since power-up as 64bit number. &#8220;Aha!&#8221;, you say, &#8220;this is it.&#8221; The trouble is that the ticks are relevant only to the CPU on which the code is running. On a multi-processor system, the thread can run on any CPU and the CPUs do not have the same number of ticks. Dang!</p>
<h2>OS functions</h2>
<p>Your only option is to use the functions of the operating system. On Windows, you can call <code>QueryPerformanceCounter()</code>; on UNIX, you can use <code>gettimeofday(...)</code>. These methods will give you roughly microsecond accuracy, which is usable for measuring sub-millisecond code.</p>
<h2>Measuring critical code</h2>
<p>The catch is that the impact of the measurement code can distort the numbers. The way around it is to calculate the measurement time overhead (per call, using compile- or load-time weaving) and then record the performance and the number of calls. Then you can subtract the expected overhead from the measured value, giving you reasonably accurate number.</p>
<h2>AOP</h2>
<p>Let me give you head start:</p>
<pre><code>
@Aspect
public class PerformanceMonitoringAspect {
    private final long THRESHOLD = 500L;  // 500 ns
    private final long callCount = 0;

    @Pointcut("execution(* net.cakesolutions.citi..handler.*.*(..))")
    private void handlerMethodExecution() { }

    @Around("handlerMethodExecution()")
    public Object performanceCollector(ProceedingJoinPoint pjp) throws Throwable {
        this.callCount++;
        long start = HighPerformanceTimer.getNanoTime();
        try {
            return pjp.proceed();
        } finally {
            long elapsed =
                (HighPerformanceTimer.getNanoTime() - start) -
                callCount * 4; // call time correction
            if (elapsed > THRESHOLD) writePoorPerformanceLogEntry(pjp);
        }
    }

    private void writePoorPerformanceLogEntry(ProceedingJoinPoint pjp) {
        System.out.println("Slow!");
    }
}
</code></pre>
<p>If you need any more information, contact me at Cake or come over to the next <a href="http://www.springusergroup.org.uk">Spring User Group</a> meeting, bring some <a href="http://en.wikipedia.org/wiki/Purple_cauliflower">purple cauliflower</a> and I&#8217;ll talk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2008/11/19/sub-millisecond-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

