Using Grails with CDI/Weld

March 4, 2011

Two of the libraries I’m most interested in lately are Grails and CDI/JSR299 (Weld being the implementation). The problem is that the two are really not compatible directly with each other. First, CDI is a JavaEE6 technology requiring a compliant container (ie: Glassfishv3) whereas Grails can run in any servlet container (plain ol’ WAR). Second, Grails uses Spring for its dependency injection system which does not really support CDI. However, in an ideal world, it would be nice to mix them as CDI makes a great backend framework while Grails makes a great frontend framework. So, what do we do to make these co-exist?

(more…)

0

Project Lambda: Closures, Extensions, Mixins, Oh My!

January 5, 2011

NOTE: Documentation and code presented here is based on living and changing documentation by the JSR committee and subject to change causing this article to be inaccurate or outdated. I am also not affiliated with the JSR or its members.

This blog article is probably a bit premature being it is centered around JDK 8, but I think it is interesting enough to cover when planning new frameworks. JDK 8 is not being planned for release until late 2012. Anyways, bare with me. One of my favorite expected features is around Project Lambda (http://openjdk.java.net/projects/lambda/). Project lambda is all about adding “closures” or “lambda expressions” to the Java language. Many people know about closures from several other languages (C#, Ruby, Groovy, etc), but not many know about how Java plans to implement them. The mechanism Java has selected to use has some interesting caveats and useful features.

(more…)

0

Beejive Supports MSN Multiple Points of Presence

January 4, 2011

One of my favorite paid applications on the iPhone is Beejive. It is a standard IM client for several IM services including MSN, Jabber/Google Talk, Yahoo, etc. Despite it being $10, it was my best $10 invested. It has allowed me to remove the $5+ dollars a month of text messaging (since all my friends have IM on their phones as well), so it paid for itself in 2 short months. I recognize there are all sorts of free options, but none of them work as effectively as Beejive. Beejive is more stable, more features, better support, and looks just so much nicer.

Anyways, one of the features I really wanted was multiple sign-on support for MSN/Windows Live (otherwise known as multiple points of presence). I hate having to login to MSN from my desktop and then remember to login from my phone once I leave. I would much rather just leave both on and have it send messages to both depending where I am. Jabber/Google Talk has had this feature for a while, which has been great. That being said, this week they finally rolled out that feature for MSN. I’m not sure too many other clients for MSN/Windows Live supports this, which furthers my investment of $10 being worth it.

My recommendation is to try Beejive out. It definitely has a great feature set and is much better for IM than SMS/MMS is.

0

State of Web Performance 2010 (via Steve Souders)

December 28, 2010

Steve Souders recently published his State of Performance for the web for 2010. This is a well written state of where we have been in improving and capitalizing on performance of web applications and web sites in general. It also goes into plans and hopes for 2011. I personally am excited about the continual progression towards web performance. It is finally becoming a reality that performance does indeed make a difference, generate revenue, and increase traffic flow. Not only does it matter on the backend technologies (databases, architecture, SOA, JSON, etc), but it also matters heavily on the frontend side. I heavily recommend reading this article as well as following Steve Souders blog.

Thanks and remember that performance matters!

1

How Many Ways to Say “Hello World”

December 20, 2010

So, I’ve been intending on writing this silly article for awhile, but have not got around to it until today. Anyways, every time I hear someone mention a new language and then look into it, the first thing I notice is how they print the standard “Hello World” statement to the screen. After the first few times, I just put it aside and ignored it. But then I started noticing a more annoying trend: nearly every language uses a new verb to express “Hello World” (I’m convinced developers are doing this on purpose now). So, my question is: how many ways can we say “Hello World”? For once, it would be nice if we had some consistency and languages used the same verbs for similar practices. If I had a dime for every time I picked the wrong verb because of switching to a different language, I could probably quit my job. Switching in and out of languages now is a daily part of any Software Developer’s job. No one language works for every situation. You should always pick the language to do the best job (but that’s another article for another time). Plus, printing to the screen is not the only inconsistency we have. Simple things like trimming (chop, trim, etc) or taking a substring (sub, substr, substring, etc) have several variants. It really gets annoying as you learn more and more languages. I’m not saying languages should not have their differences; obviously they should. That is what makes them unique and powerful in their own ways. All I’m saying is for things as simple and common as printing to the screen, let’s all agree on a standard verb. Please! :)

Anyways, that being said, here is my list I have been compiling. Drop me a comment if you can think of others and I will update the list accordingly. It would be interesting to see just how many ways we can truly say “Hello World”!

Verb Language(s)
System.out.println Java
echo PHP, Bash
cout C++
print Perl, PHP, BeanShell, Lisp, Python
Console.WriteLine Visual C#
document.write Javascript
println Groovy, Scala
puts Ruby, Tcl/Tk
printf C, Objective-C
io:formar Erlang
write Fortran, Prolog
Writeln Pascal
display Scheme
1

Java Performance: Map vs If/Else

December 17, 2010

I came across an interesting javascript article the other day on how not to write javascript: Google Closure: How not to write JavaScript

The interesting part of this article that caught my eye was using a map instead of a switch or if/else statement to check for string comparisons. This got me thinking of whether the same would hold true for Java. So, the question is ” which is faster: using an if/else to match results or map-based operations”? At first thought, you might think if/else since the VM optimizes the bytecode and there is no requirement to setup a call stack to invoke a method. However, if/else has to use equals which must walk the string characters matching each one. In the case of maps, they are optimized for fast lookups using buckets via the hash codes. Thus, you generally only have a few instances to invoke equals against rather than each one (in the case when a value is last in the list). So let’s get to the results…click to continue reading.
(more…)

2

Building Annotation-Driven Configuration

December 7, 2010

In the last few years, annotation-driven libraries have been on the rise in new and even existing libraries. Rather than use configuration files such as XML or properties, libraries now make use of annotations in JDK 5 to mix the configuration directly inline with the code. This simplifies the configuration by not having to maintain a separate configuration file. The purpose of this article is to explain a brief sample of how to build an annotation-driven configuration processor. Click to continue reading.
(more…)

0

Follow Me on Twitter / Blog Update

November 25, 2010
Tags:

I decided to finally sign up for Twitter. For those who know me, know I am not a fan of social networking. However, I can see the value in Twitter as an aggregation service. That being said, my blog will now push updates to Twitter. So, if you follow me on Twitter, you will have an easier way of knowing when my blog gets updated.

Speaking of blogs, this year I’m going to put more priority around writing in it especially focusing on some newer libraries and next generation concepts. If you have an idea of something you would like me to research and blog about send me a comment and I will consider doing it.

Here is a short list I’m going to get to real soon:

  • Generating Code Dynamically
  • Reflection Analysis
  • Templating Languages
  • JDK 7/8 Features
  • CDI Features (vs Spring)
  • Javassist vs CGLib
  • Mobile WebKit Accelerometer
  • AJAX 2
  • Node.js
  • XMPP / Monitoring Tools
  • Groovy / Grails
  • Hadoop / HBase

Thanks

0

Creating Transactional Proxy Classes

July 10, 2010

One of the frequent patterns I make use of for Java backend systems are transactional code blocks, and not transactional in the sense of JPA, Hibernate, Databases, etc. I mean generic transactional blocks in which you have to wrap a piece of code with a begin and end block. For example, JPA is just one style in which you invoke:

try {
    em.getTransaction().begin();
    // invoke code
} finally {
    em.getTransaction().end();
}

Another common example is using pools in which you must borrow and return objects such as:

Object data = null;
try {
    data = pool.borrowObject();
    // do something
} finally {
    pool.returnObject(data);
}

These are just common examples. Often times, I have my own type of transactional block that references some other type of system that must maintain a begin and end state. However, even as simple as

try { begin(); } finally { end(); }

is, it can easily be screwed up. For example, a common mistake is forgetting to put the end() in a finally block to ensure it runs. Further, it violates the DRY (don’t repeat yourself) principle such that if you need to change the processing a bit, you would need to change every invocation of begin/end. That creates a possible maintenance issue.

So, how do we avoid using transactional blocks? The easiest solution is something that most modern libraries such as Spring or Java EE already do, which is creating proxy classes to invoke the blocks automatically. If you are already using Spring or Java EE, you prolly already do this with the @Transactional annotation. However, this post will help demonstrate a simple and easy method of achieving this same behavior for custom transactional blocks.

The first step is creating a marker annotation that will be used on classes and methods to denote a transactional block of code. For example:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public static @interface Transactional {
    // annotation specific values
}

This annotation allows us to mark either a class or a method. This is basically what the Spring/Java EE Transactional annotation does. The next thing we need to do is actually mark methods as transactional. We can do this either at the class level meaning every method in the class will be transactional or at the method level. The choice is completely a personal preference. However, if you mark the class, then you can ensure that every method will be transactional even if you add a new method. That will help reduce the accidental likelihood of adding a new method but forgetting the transaction annotation. However, if you do not want certain methods to be wrapped in a transactional block, then you will need to annotate at the method level one by one. Here is an example:

@Transactional
public class Test1 {
     public void method1() {
          // this will be invoked in transactional block
     }
 
     public void method2() {
          // so will this
     }
}
 
public class Test2 {
     public void method3() {
          // this will not be transactional
     }
 
     @Transactional
     public void method4() {
          // but this will
     }
}

Now that we have our transactional code we need to create proxy classes to automatically wrap the code. My preferred way of achieving this and the purpose of this blog is to use CGLIB proxy classes. There are several other ways to achieve such as AspectJ. I will leave learning those ways to the reader. Anyways, back to CGLIB. CGLIB provides a proxy creation class called Enhancer. It is very similar to the Proxy class in the standard Java reflection package. However, there is one major difference. The standard Java Proxy class may only use and proxy interfaces, not concrete classes. Enhancer and CGLIB can proxy concrete classes. It is concrete classes that are essential so that we can proxy our existing classes and wrap the methods in transactional code block. Before we can use CGLIB, we must add it to our classpath. The version I am actively using is 2.1_3. You can either download the JARs directly or use the following Maven dependency:

<![CDATA[
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_3</version>
        </dependency>
]]>

Once you have added CGLIB, here is the basic way of creating those blocks:

public class Transactions {
        @SuppressWarnings("unchecked")
        public static <T> T proxy(final T object) {
            // check if transactional specified at class level of class or 
            // any parent classes or interfaces
            boolean isTransactional = false;
            Class<?> parent = object.getClass();
            while (!isTransactional && parent != null) {
                if (parent.getAnnotation(Transactional.class) != null) {
                    isTransactional = true;
                }
 
                for (Class<?> ifclass : parent.getInterfaces()) {
                    Class<?> ifparent = ifclass;
                    while (!isTransactional && ifparent != null) {
                        if (ifparent.getAnnotation(Transactional.class) != null) {
                            isTransactional = true;
                        }
 
                        ifparent = ifparent.getSuperclass();
                    }
                }
 
                parent = parent.getSuperclass();
            }
 
            // create proxy class from concrete class
            final boolean transactional = isTransactional;
            return (T) Enhancer.create(object.getClass(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args)
                        throws Throwable {
 
                        // check if transactional at class level or if current method
                        // is transactional.  Note that this ignore overrides.  You
                        // may want to extend this to search for all subclasses and
                        // interfaces defining the method and check those annotatations
                        // as well
                        if (transactional ||
                            method.getAnnotation(Transactional.class) != null) {
                            try {
                                // start transaction block
                                // this could be anything you needed to do such as borrow
                                // from a pool, etc
                                Transactions.begin();
 
                                // invoke method and return its value if provided
                                return method.invoke(object, args);
                            } finally {
                                // finalize the block
                                // this should be the corresponding end block to the begin block
                                Transactions.end();
                            }
                        }
 
                        // not transactional, so invoke as normal
                        else {
                            return method.invoke(object, args);
                        }
                    }
                });
        }
}

Now that we have that code in place, we can create proxy classes and invoke the methods without worrying about the transactional blocks. Going back to our initial test class, we could invoke via:

    Test1 test = Transactions.proxy(new Test1());
    test.method2(); // this will be invoked in a transactional block

That’s all there is to it.

2

Simple Performance Improvement with Large Ehcache Disk Store Data Sets

April 29, 2010

One of my applications has several millions cacheable entries.  In order to cache as much as possible without going back to the database I use both a  memory store and a disk store in my Ehcache configuration.  Loading a serialized item from disk is still faster than loading from a database generally.  That being said I was running into performance issues due to the constant reads and writes to and from the disk store.   Due to the serialized nature of the data file it would block on subsequent accesses resulting in lag and performance issues.  So, how did I address it?  I decided to partition the single cache into multiple caches.  So, rather than using something like:

ehcache.getRegion(CONSTANT).get(id);

I now use:

ehcache.getRegion(CONSTANT + (id % 10));

I now have 10 different cache regions resulting in less concurrent access and better performance.  A very simple trick when you have extremely large data sets.  Remember, partitioning is always your friend regardless of what type of data you use.

UPDATE: This is being done in Ehcache 1.5.0…I understand there are better improvements in Ehcache 2.x, so please consult the documentation for more information.

3