Category Archives: Uncategorized

Better compareTo() syntax

I’ve never really been a big fan of the syntax of java.lang.Comparable.compareTo(). For some reason I find myself constantly referring to the JavaDocs to remind me whether < 0 or > 0 means the argument is less vs more than the callee.

So I decided to do something about it, and created a minimal API with the sole purpose of improving readability of compareTo().

The API supplies methods in two flavors, expressive or abbreviated. The expressive version looks like this:

import static;

  boolean oneIsZero = is(1).equalTo(0);
  boolean aIsNotZero = is(a).notEqualTo(0);
  boolean bIsZero = is(b).zero();
  boolean value1LessThanValue2 = is(value1).lessThan(value2);
  if(is(a).lessThanOrEqualTo(b)) {

  boolean date1AfterDate2 = is(date1).greaterThan(date2);

  if(is(a).greaterThanOrEqualTo(b)) {


The abbreviated syntax looks like this:

import static;

  boolean oneIsZero = is(1).eq(0);
  boolean aIsNotZero = is(a).ne(0);
  boolean value1LessThanValue2 = is(value1).lt(value2);

  if(is(a).le(b)) {

  boolean date1AfterDate2 = is(date1).gt(date2);

  if(is(a).ge(b)) {


The API is available on Maven Central:


Source are on GitHub.

Manual download here.

Debugging third party libraries with AspectJ and Maven

Once in a while you may find yourself in a situation, where you need to debug a third party library on a production server or other environment where it is not possible or impractical to attach a debugger. It may also be the case that modifying the sources of that library and compiling a custom version is not an option (due to compilation dependencies, licenses, source not available or whatnot).

I found myself in such a situation a while back when I needed to understand memory leaks in OpenOffice JURT. I achieved this by injecting debug logging into the library with AspectJ, and in this post I will describe how.

In my situation the third party library was a transitive Maven dependency. In order to weave this library with my own aspects, I added this to the pom.xml:

          <!-- Weave third party dependency -->
        <!-- Weave on compile -->

Note! In order for the weaved version of the library to be included in your .war, the above should be located in the web module if your Maven project has multiple modules. If your aspect is in another module you also need to add


to the configuration.

You’ll likely also want to add the AspectJ runtime dependency, for the aspect implementation.


Now lets move on with the actual aspect. If you need an introduction to AspectJ, you may find this post useful. First we have our aspect class:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 * AspectJ aspect used for debugging memory leaks caused by OpenOffice JURT
 * @author Mattias Jiderhamn
public class JURTDebugAspect {
  private static final Logger LOG = LoggerFactory.getLogger(JURTDebugAspect.class);

  /** Utility method to get StackTraceElement of caller */
  private static StackTraceElement getCaller(int levels) {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    return stackTrace[levels + 1];


Inside that aspect class, we can add different joinpoints and advice to inject logging.

  public void addCalled() {
    LOG.warn("JURT: add() called by " + getCaller(3));

This will log calls to the third party API add() method, including calls from other third party libraries. Note that “execution” pointcut is used rather than “call” pointcut, since we are weaving the callee, not the caller. The getCaller() utility method also allows us to see what code called the add() method.

  @Before("call(* java.lang.Thread.start(..)) && within(*) && target(thread)")
  public void threadStarted(Thread thread) {
    LOG.warn("JURT: Thread.start() called by " + getCaller(2) + " on thread named " + 
      thread.getName() + " of type " + thread.getClass().getName());

Here we add some logging for when the third party library calls the start() method on java.lang.Thread, and include the name and type of the started thread.

  @Around("call(*$ && within(*) && target(job)")
  public Object jobRun(ProceedingJoinPoint proceedingJoinPoint, Object job) throws Throwable {"JURT: starting: " + job.getClass().getName() + " in thread " +
    final long start = System.currentTimeMillis();
    try {
      return proceedingJoinPoint.proceed();
    finally {"JURT: done: " + job.getClass().getName() + " in thread " +
        Thread.currentThread().getName() + "; took " + 
        (System.currentTimeMillis() - start) + " ms");

Here we log internal calls to inside the API, and measure the time that those calls take. The name of the Job subclass is included.

Good luck debugging third party libraries!

Unexpected side effect of LambdaJ aggregates

I have been using LambdaJ (2.3.2) for a couple of weeks now. It’s a simple yet impressive API that you should read more about if you’re not using it already.

One of the features of LamdaJ are aggregates, with which you can do stuff like the following. Assuming a class

class Person {

  // name etc ...  

  int age;

  public int getAge() {
    return age;

  public void setAge(int age) {
    this.age = age;


you could then do

Person twelveYearsOld = new Person();
Person fiftyYearsOld = new Person();
List<Person> persons = Array.asList(twelveYearsOld, fiftyYearsOld);

int maxAge = maxFrom(persons).getAge(); // Will be 50
int minAge = maxFrom(persons).getAge(); // Will be 12
int sumAge = sumFrom(persons).getAge(); // Will be 62

The other day I used sumFrom() for the very first time, in a layer of our application where we do not (yet) apply TDD. When I ran a manual test of the changed code, I got an exception informing me that updates could not be made in a read-only transaction! Well yes, the transaction surrounding the code that I changed was read-only, but I hadn’t made any updates to my Hibernate entities…? It didn’t take too long to narrow it down to the LambdaJ sumFrom() being what triggered the exception (which was thrown in the Hibernate flush made at transaction commit). It took me a while longer to understand what was going on. It was a bit interesting, so I will try to explain it to you.

LambdaJ uses proxies for some of its functionality, such as aggregates. If the type argument of the collection (Person in the above example) is an interface, a regular Java Proxy is used. If however the type argument is a class – as in our case above – then LamdaJ will make use of cglib which will perform runtime bytecode instrumentation. This results in a “secret” subclass of the type argument class, for which method calls are sent to a MethodInterceptor which works just like an InvocationHandler for a regular interface based Proxy (LambdaJ’s InvocationInterceptor implements both interfaces).

In the case of LambdaJ aggregates, any method calls to the proxy will be invoked on all the objects in the collection, and the return values will be assembled by some Aggregator (min, max, average, sum etc).

This still does not explain the behavior I was seeing, does it? No, because I left out a part, which I finally realized to be the explanation. In my case the data class had properties that were initialized with default values, not at the declaration and not with a simple assignment, but with a caller to setters in the default constructor. That is, as if the Person class above had

class Person {


  public Person() {
    this.setAge(20); // Set default age to 20 ("this" is explicit for clarity)



Since cglib proxies are subclasses of the original class, it means that creating an instance of this proxy class will invoke the default constructor of it’s base class. If there are method calls from within the constructor on the object itself, these method calls will also be taken care of by the MethodInterceptor. In the case of LambdaJ, this means that the method call in the constructor will be issued on all the objects in the collection…

Reusing the example above, with Person having it’s new constructor, the result is this

List<Person> persons = Array.asList(twelveYearsOld, fiftyYearsOld);

int maxAge = maxFrom(persons).getAge(); // Will be 20!
int minAge = maxFrom(persons).getAge(); // Will be 20!
int sumAge = sumFrom(persons).getAge(); // Will be 20!
int age12 = twelveYearsOld.getAge(); // Will be changed to 20!!!
int age50 = fiftyYearsOld.getAge(); // Will be changed to 20!!!

The workaround in this case is very simple: Don’t call setters from the constructor. Instead use “inline” property assignment (this.age = 20).

Unfortunately, in our project we have lot’s of classes with default values set by calling setters in the constructor. Therefore I created a patch for LambdaJ, which “deactivates” the InvocationInterceptor (or rather the concrete ProxyIterator subclass) while cglib proxy creation is in progress, and activates it before the proxy is returned for use. Hopefully the fix will make it into LambdaJ 2.3.3.