Jan 16

For, for each, while : What is the difference?

In Java you have several ways to iterate through a collection. This article is not about which one to choose but more about understanding which one does what. For those who are looking for an article telling them which one is the best : Stop searching and start coding! Pick the most elegant one depending on your situation.

Measuring Performance

I have developped a micro-benchmark to compare the different kind of iterations over a List. You can find the full source code on my github, but let’s have a look at the different method to iterate through a List.

//WHILE with iterator
                int sum = 0;
                Iterator<Integer> it = list.iterator();
                while (it.hasNext()) {
                    sum += it.next();
                }

// For with iterator
                sum = 0;
                for (Iterator<Integer> it = list.iterator(); it.hasNext();) {
                    sum += it.next();
                }

//for each syntax
                int sum = 0;
                for (Integer i : list) {
                    sum += i;
                }

//while increment
                int sum = 0;
                int i = 0;
                while (i < list.size()) {
                    sum += list.get(i);
                    i++;
                }
//for Increment
                int sum = 0;
                for (int i = 0; i < list.size(); i++) {
                    sum += list.get(i);

                }

Let’s measure the performance of by iterating over a list and doing the sum of a list of 1000 integers. On my machine it gives :

 benchLoops

Interpreting the benchmark results

The charts Y-Axis is in nano-seconds, so for the first chart, we can fairly say that all kind of iterations are similar. Even if we can notice that the two last scenarios are a bit faster.

The second chart shows that, for a LinkedList, the last two scenarios are way longer than the others.

If we look at the disassembled class files, available on my github, we can see that the firsts 3 scenarios are almost compiled to the same instructions (there is actually some very small differences that don’t affect the performances). All of them will call the iterator method of the List and then use the hasNext and next methods. The generated class file for the two lasts scenario are also almost identical. We can see that LinkedList is very bad at getting random elements with get(int) and in this case, it is better to use the iterator method.

Conclusion

Basically there is two strategy : using the fact that a collection implements Iterable or using some methods specific to the implementation (like get(int for a List)).

In my opinion, you should ALWAYS use the iterator method because :

  • It can be used with all collections; If you want to change a List by a Set, you can!
  • All collections implementations have their own optimized version of the Iterator, it should always be the most (or near) efficient way to iterate through the collection

Then choosing between the while, for or for each version is just a matter of taste, it won’t change anything to the functionality.

Also if you need a loop counter you can do :

int sum = 0;
int i =0;
for (Iterator<Integer> it = list.iterator(); it.hasNext(); i++) {
   sum += it.next();
}

 

For more details about the class files generated, I have posted a disassembled version of the class files on my github, next to the code.

Posted in Java Core | 2 Comments
Oct 18

StringBuffer VS StringBuilder by example : commons-lang3. Does it make so much differences?

Recently, I was using the ToStringBuilder class of commons-lang3 and realised that they were still using StringBuffer and not StringBuilder.

I am always using ToStringBuilder (or ReflectionToStringBuilder) like that :

    @Override
     public String toString() {
        ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE);
        builder.append("field1",field1);
        builder.append("field2",field2);
        builder.append("field3",field3);
        return builder.build();
    }

I don’t need ToStringBuilder to be thread safe since I use it locally. In my case, if ToStringBuilder was using a StringBuilder internally instead of StringBuffer, it wouldn’t lead to any concurrency issue and it would improve the performance. Actually, I don’t see any reason to use a ToStringBuilder in a multi-thread context…

As this issue suggests, should commons-lang3 should do a refactor for that??

Since we often talk about the importance of using StringBuilder instead of StringBuffer in non thread safe context, I believe that it was a good opportunity to compare the performance of StringBuilder VS StringBuffer.

StringBuilder VS StringBuffer : Comparing the performance

To compare the performance I have used Caliper. I haven’t done an extensive test suite, my goal is just to give the big picture. For this test, I have rewritten ToStringBuilder and ToStringStyle (respectively UnsafeToStringBuilder and UnsafeToStringStyle) to use StringBuilder. You can check my implementation on my github.

public class TestPerfStringBuild extends SimpleBenchmark {

    private static int NB_THREAD_POOL = 5;

    private static Runnable WITH_STRING_BUFFER = new Runnable() {
        @Override
        public void run() {
            for (int j = 0; j < MyObject.testObjects.length; j++) {
                MyObject o = MyObject.testObjects[j];
                new ToStringBuilder(o, ToStringStyle.DEFAULT_STYLE)
                        .append("field1", o.getField1()).append("field2", o.getField2()).append("field3", o.getField3()).build();
            }
        }
    };
    private static Runnable WITH_STRING_BUILDER = new Runnable() {
        @Override
        public void run() {
            for (int j = 0; j < MyObject.testObjects.length; j++) {
                MyObject o = MyObject.testObjects[j];
                new UnsafeToStringBuilder(o, new UnsafeToStringStyle(){})
                        .append("field1", o.getField1()).append("field2", o.getField2()).append("field3", o.getField3()).build();
            }
        }
    };

    private static void sequentialRun(int reps, Runnable r){ for (int i = 0; i < reps; i++) r.run(); }
    private static void multiThreadRun(int reps, Runnable r) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(NB_THREAD_POOL);
        for (int i = 0; i < reps; i++) pool.submit(r);
        pool.shutdown();
        pool.awaitTermination(20, TimeUnit.SECONDS);
    }

    public void timeLogStringBuffer(int reps) {
        sequentialRun(reps, WITH_STRING_BUFFER);
    }

    public void timeLogStringBuilder(int reps) {
        sequentialRun(reps, WITH_STRING_BUILDER);
    }

    public void timeMultiThreadLogStringBuffer(int reps) throws InterruptedException {
        multiThreadRun(reps, WITH_STRING_BUILDER);
    }

    public void timeMultiThreadLogStringBuilder(int reps) throws InterruptedException {
        multiThreadRun(reps, WITH_STRING_BUILDER);
    }

    public static void main(String[] args) {
        System.out.println(MyObject.testObjects); // init testObjects
        Runner.main(TestPerfStringBuild.class, new String[]{"--warmupMillis", "3000", "--runMillis", "5000"});
    }

}

class MyObject {
    private final String field1;
    private final int field2;
    private final Object[] field3;
    public static final MyObject[] testObjects;

    static {
        testObjects = new MyObject[]{
                new MyObject("field1", 2, "field", "3", "iugacsgiuasgiusaiu", "hcgavusfaucsavusva", "", "wsx"),
                new MyObject("idgsiugidsdds", Integer.MIN_VALUE, new HashMap<String, String>() {{ put("aa", "bb"); put("dfsfs", "uycdsgfds");}}),
                new MyObject("AnOtherExample", Integer.MAX_VALUE),
                new MyObject("AnOtherExampleLonggg", 0, null, null)
        };
    }

    private MyObject(String field1, int field2, Object... field3) {
        this.field1 = field1;
        this.field2 = field2;
        this.field3 = field3;
    }

    public String getField1() {return field1;}
    public int getField2() { return field2; }
    public Object[] getField3() { return field3; }
}

StringBuilder VS StringBuffer : The result

 0% Scenario{vm=java, trial=0, benchmark=LogStringBuilder} 4045.24 ns; σ=67.05 ns @ 10 trials
25% Scenario{vm=java, trial=0, benchmark=LogStringBuffer} 4205.23 ns; σ=23.62 ns @ 3 trials
50% Scenario{vm=java, trial=0, benchmark=MultiThreadLogStringBuilder} 2363.86 ns; σ=408.40 ns @ 10 trials
75% Scenario{vm=java, trial=0, benchmark=MultiThreadLogStringBuffer} 2487.25 ns; σ=389.37 ns @ 10 trials

                  benchmark   us linear runtime
           LogStringBuilder 4.05 ============================
            LogStringBuffer 4.21 ==============================
MultiThreadLogStringBuilder 2.36 ================
 MultiThreadLogStringBuffer 2.49 =================

The performance of ToStringBuilder.append can be counted in nano-seconds…  On top of that, using a StringBuilder improve the performance by less than 5%.

Conclusion

StringBuilder is faster than StringBuffer but the difference is in nano-seconds… The epoch were synchronized was expensive is far! Of course it’s better to use StringBuilder in non multi-thread contexts but don’t take into account the performance to make your choice.

Commons-lang3 is an ultra-popular API, breaking this API, and so force thousand of clients to do a refactor, to save few nano-seconds doesn’t make sense.

Posted in Uncategorized | 3 Comments
Sep 25

Do Immutability really means Thread Safety?

I have often read articles telling “If an object is immutable, it is thread safe”. Actually, I have never found an article that convinces me that immutable means thread safety. Even the book by Brian Goetz Java Concurrency in Practice with its chapter on immutability did not fully satisfied me. In this book we can read word for word, in a frame : Immutable objects are always thread-safe. I think this sentence deserve more explanations.

So I am going to try to define immutability and its relation to thread safety.

Definitions

Immutability

My definition is “An immutable object is an object which state does not change after its construction”. I am deliberately vague, since no one really agrees on the exact definitions.

Thread safety

You can find a lot of different definition of “thread safe” on internet. It’s actually very tricky to define it. I would say that a thread safe code is a code which has an expected behaviour in multi-thread environment. I let you define “expected behaviour”…

The String example

Lets have a look at the code of String (actually just a part of the code…):

public class String {
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    public String(char[] value) {
        this.value = Arrays.copyOf(value, value.length);
    }

    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
}

String is considered as immutable. Looking at its implementation, we can deduct one thing : an immutable can change its internal state (in this case, the hashcode which is lazy loaded) as long as it is not externally visible.

Now I am going to rewrite the hashcode method in a non thread safe way :

    public int hashCode() {
        if (hash == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                hash = 31 * hash + val[i];
            }
        }
        return hash;
    }

As you can see, I have removed the local variable h and affected the variable hash directly instead. This implementation is NOT thread safe! If several threads call hashcode at the same time, the returned value could be different for each thread. The question is, does this class is immutable? Since two different threads can see a different hashcode, in an external point of view we have a change of state and so it is not immutable.

We can so conclude that String is immutable because it is thread safe and not the opposite. So… What’s the point of saying “Do some immutable object, it is thread-safe! But take care, you have to make your immutable object thread-safe!”?

The ImmutableSimpleDateFormat example

Below, I have written a class similar to SimpleDateFormat.

public class VerySimpleDateFormat {

    private final DateFormat formatter = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);

    public String format(Date d){
        return formatter.format(d);
    }
}

This code is not thread safe because SimpleDateFormat.format is not.

Is this object immutable? Good question! We have done our best to make all fields not modifiable, we don’t use any setter or any methods that let suggest that the state of the object will change. Actually, internally SimpleDateFormat change its state and that’s what makes it not thread safe. Since something change in the object graph, I would say that it’s not immutable, even if it looks like it… The problem is not even that SimpleDateFormat changes its internal state, the problem is that it does it in a non-thread safe way.

Conclusion of this example, it is not that easy to make an immutable class. The final keyword is not enough, you have to make sure that the object fields of your object doesn’t change their state, which is sometimes impossible.

Immutable objects can have non thread-safe methods (No magics!)

Let’s have a look at the following code.

public class HelloAppender {

    private final String greeting;

    public HelloAppender(String name) {
        this.greeting = "hello " + name + "!\n";
    }

    public void appendTo(Appendable app) throws IOException {
        app.append(greeting);
    }
}

The class HelloAppender is definitely immutable. The method appendTo accepts an Appendable. Since an Appendable has no guarantee to be thread-safe (eg. StringBuilder), appending to this Appendable will cause problems in a multi-thread environment.

Conclusion

Making immutable objects are definitely a good practice in some cases and it helps a lot to make thread-safe code. But it bothers me when I read everywhere Immutable objects are thread safe, displayed as an axiom. I get the point but I think it is always good to think a bit about that in order to understand what causes non-thread safe codes.

Thanks to the comment of Jose, I end up this article with a different conclusion. It’s all about the definition of immutable. It needs clarifications!

An object is immutable if :

  • All its field are initialized before being used (which means you can do lazy initialization)
  • The states of the field does not change after their initialization (does not change means that the object graph doesn’t change, even the internal state of the children)

An immutable object will always be thread-safe unless it deals it has to manipulate non thread safe objects.

Posted in Java Core | Tagged , | 7 Comments
Sep 13

Java SE 11 : Moving Java Forward – Part 3 : Thread Safe compilation checking

This serie of article presents how, in my opinion, the java language should evolve to keep being a top choice language. It also presents some features, sometimes already existing in other language, that I love but that cannot (or should never) be part of Java, for some reasons that I will explain. I would really love to transform some of those ideas into JSRs one day.

Thread Safe compilation checking : What is it?

It is the ability to check that your program will not have issues due to multi-threading. As far as I know, no programming language provide this functionality (If you know one, please let me know!).

What is the problem?

Develop a program that runs in several threads is easy, develop something that won’t have any weird bugs due to that thread mechanism is far more difficult.

Why concurrent programming is hard?

Because, to make a good multi-thread application, you have to be very careful and to know perfectly the Java language and the API : avoid deadlocks, know when to use the volatile keyword, know what is (or not) thread safe.

The other difficulty is that testing/debugging a multi-thread application is very hard. You can spend several days wondering why in your huge database you have this row with a weird date value… To finally realize that your co-developper (of course not you, since you are a java guru ;) ) has used a SimpleDateFormat object shared by several thread… (BTW, if you didn’t know: yes, SimpleDateFormat is not thread safe)

What is the solution?

The thread safe compilation checking! It would make the development so much easier if you had a warning telling you “At line 36: Not Thread Safe code. Usage of a non thread safe method SimpleDateFormat.format”.

Why It is impossible

Usage of non thread safe APIs

At the moment, the only way to know if the libraries/APIs you are using are thread safe is to read Javadoc or the source code. So, the compiler has no way to know if what you call is, or is not, thread safe. By transitivity, if you are not using any kind synchronisation mechanism,  it has no way to know if your code is thread safe or not since you are using those libraries.

One solution to this issue could be to create a @ThreadSafe annotation to annotate classes and methods. That way, any element annotated with @ThreadSafe would be considered as thread safe by the compiler. Of course all the APIs you use needs to be annotated correctly… Apart from the compilation checking thing, I think that such an annotation would be great to make the APIs clearer.

The Reflection API

The Reflection API is an other issue. Since the execution flow is determined during the runtime, the compiler cannot know what methods will be called and so cannot determine if what is going to be executed is thread safe.

The compiler needs to know the context

The compiler has no way to know if what you are developing is going to be executed in a thread safe environment or not. For example if you are developing a bean that is going to be injected everywhere by your favorite CDI framework, the compiler cannot know it.

In other words, the compiler knows less than you and so cannot determine if what you are programming needs to be thread safe or not. Let’s say you are programming a controller for your J2EE application; If you don’t annotate your controller with the hypothetic @ThreadSafe annotation, the compiler won’t ever complain. The problem is that your controller have to be thread safe! If you don’t annotate correctly with @ThreadSafe what had to be thread safe, you will have issues…

The different locks mechanism

If the only way to synchronize your threads was the synchronized keyword, it would be easier for the compiler to determine if a piece of code can be run concurrently or not. Unfortunately that is not the case! You have several way to ensure that your code will be executed only in the right context (ReentrantLockReadWriteLock, manual locks using a file, a socket, an object, a counter etc…). To me, this only reason makes the “thread safe compilation checking” impossible to implement. If the compiler is not able to spot  the synchronisation mechanism, it cannot know anything about thread safety!

Conclusion

Thread safe compilation checking would definitely be a killer feature. But to me, it is impossible to implement, even partially, and that’s probably why I have never seen this feature in any languages.

If you have any ideas of a solution or if you know any language that does it, even partially, let me know!

 

Posted in Java Core | Tagged , | 1 Comment
Jul 24

Java SE 11 : Moving Java Forward – Part 2 : Properties accessor

This serie of article presents how, in my opinion, the java language should evolve to keep being a top choice language. It also presents some features, sometimes already existing in other language, that I love but that cannot (or should never) be part of Java, for some reasons that I will explain. I would really love to transform some of those ideas into JSRs one day.

Accessing fields of an object through a transparent accessor is definitely THE feature I miss in Java.

What is it?

In Java, we use to use getters and setters which allow to access a property of an object. I will not speak of the benefits of having getters and setters instead of having public fields, I assume that you are aware of that… In other languages (C#, AS3, …), you can declare explicitly the getter and setter of a property and use them as if you were using a public property. My favorite syntax is the one ActionScript3 :

//Object Declaration
public class MyObject {
       private var _myProperty:String;

       public function get myProperty():String {
                return _myProperty;
       }

       public function set myProperty(value:String):void {
              _myProperty = value;
       }

       public function get firstLetter():String {
               return _myProperty.substr(0,1);
       }
}

//Usage
var o:MyObject = new MyObject();
o.myProperty = "A value"; //Set the property using the setter
trace(o.myProperty); //Print the value return by the getter
trace(o.firstLetter); //Print 'A'

The Java syntax suggestion

Since I consider the ActionScript 3 syntax very convenient, I think that the Java syntax should be very similar. It would require to add new modifiers : get and set.

public class MyObject
{

    private String _name;

    public get String name() {
        return name;
    }

    public set void name(String name) {
        this.name = name;
    }
}

//Usage
MyObject o = new MyObject();
o.name = "My name";
System.out.println("print entity : " + o.name);

Benefits

  • Using an accessor is transparent. The encapsulation is made implicit. The caller does not know if it is calling a public variable or an accessor.
  • Better OO style programming : From an external class point of vue, an object now really has public methods and properties, while before it was only public method.
  • Refactoring the code to change all direct accesses to the fields of the object is a peace of cake, you just have to change the class concerned, not all read/write calls.
  • No need anymore to have the JavaBean conventions on getter and setter. Some librairies relied on the fact that accessors of myProperty are called [get|is|set]MyProperty. Now the accesors are no more defined by convention but by contract. We can have a method on the class Class which retrieve the accessor (getGetters(), getSetters()). Once again, a big OOP enhancement.

Drawbacks

  • It would require to change the naming convention of the object fields since the method and the property could have the same name. There’s no doubt that the JVM could allow that the property and the method have the same name, it is more a readability issue.

Implementation and Issues

Implementing this feature would require to add two new keywords (get and set) to the Java language. That is a bad things for the retro-compatibility but that is not a big problem. It would need to use the “-source”  command-line option as it has been done before when the assert keyword has been added in Java 1.4.

This change would also require to modify the JVM specification, and so the java compiler, to add the two new modifiers. Those two new modifiers are needed in the class file in order to identify, using the reflection, the getters and setters of a class.

Conclusion

I believe that this feature would be an awesome improvement of the Java language. As all major improvements, it requires a lot of work. If one day I feel ready enough to submit a JSR, that will definitely be this one!

Posted in Uncategorized | 3 Comments
Jul 24

Java SE 11 : Moving Java Forward – Part 1 : Introduction

This serie of article presents how, in my opinion, the java language should evolve to keep being a top choice language. It also presents some features, sometimes already existing in other language, that I love but that cannot (or should never) be part of Java, for some reasons that I will explain. I would really love to transform some of those ideas into JSRs one day.

Over the last 15 years, the Java language and the JVM has been greatly improved. The JIT compiler, the apparition of the generics, the auto-boxing, soon (cross the fingers) the lambdas… All that features have contributed to the success of Java. But what is next? How to make Java better?

Through my experiences, I had the opportunity to work with several programming languages. This include C#, C/C++, PHP, Javascript, Groovy, ActionScript 3, Scala and some others… In many of these languages, I have found some features that made me say “that is f***ing awesome!”. Some of those features were not applicable to Java (different programmation paradigm, different way of thinking) while others were completely applicable. Also in some of these languages (mostly in PHP…), I have seen things that made me say “OMG! That’s crap!”… But that is a different story!

In each part of this serie, I will present one feature that does not exist in Java and explain why it should (or not) be in Java, the possible issues to deal with, etc…

Do not hesitate to post ideas of improvement, even the craziest/irrealistic one! I do not pretend myself to have perfect solutions, I just try to open the discussion.

Posted in Java Core | Tagged | Leave a comment
Jul 15

Java EE 6 VS Spring 3 : Java EE has killed Spring? No way!

Introduction

Few days ago, I was listening to the epsiode 85 of the Java Spotlight Podcast. In this epsiode, Bert Ertman  and Paul Bakker were talking about migrating from Spring to Java EE. Basically, in their introduction they were saying that, nowaday, there is no point choosing Spring over Java EE. We can read in their article :

It took a while but Java EE has finally made the leap to be a standard, lightweight, fitting solutions to the vast majority of real-world development challenges in the mainstream enterprise applications space. You should have no single reason beyond choosing the standard.

Over the last couple of months, I have seen a lot of blog articles with similar thoughts. Some are praisising Java EE, which is a good thing, while others are just denigrating Spring. This is the case of the article of Arun Gupta. My first thought on this article was “Oracle might be really desperate to write such trolls…”.

I am not at all a Spring evangelist nor a Java EE hater. At the contrary, I have used intensively Java EE 5 for 2 years and am really happy to see that Java EE finally became a good competitor for Spring. My goal is not to praise Spring here, just to balance the words of the “Spring’s hater”.

Standard VS Single vendor solution

Is that good to have standards?

Do you know this sentence “Responding to change over following a plan”? Yes, it is one the Agile rules. Of course it is a good thing to have standards, it is more than good, it is fundamental! But it comes with its drawbacks. If one day you have a problem with the standard, something not covered by the standard, your only solution is to fill an issue, cross your finger and wait 3 years…

Are Spring and standards incompatible?

Not at all! That is one of the reason I do not understand the “It is standard” argument. Spring does its best to provide the use of the standard. You are free to use JPA, the CDI annotation etc. I consider Spring more like an integration platform that let you use all Java EE technologies and also some additional features provided by Spring itself.

Do I depend on SpringSource? Not really…

What happen if tomorrow SpringSource stop developing Spring? I will continue using it… Spring Framework is under Apache 2.0 license, no doubt that the community will take the relay and that some new companies will offer support for Spring. Even if nobody do that, I am happy with Spring Framework in its current state, why would I change? Maybe I will reconsider it in 3 years, when a new version of Java EE will be released… ;)

What happen if tomorrow I am not happy with Spring Framework? The same thing than if I am not happy with Java EE… I stop using it…

What happen if tomorrow I am not happy with my application server? The same thing than if I am not happy with Java EE… I change it… Except that, with Spring, I will have more choices (since Spring works with all Java EE application server + the others like tomcat, jetty etc…).

Spring has always been innovative and will always be

I will never forget that Spring has made CDI possible and easy for the Java web development. Java EE has followed (again 3 years later…) with the JSR-299.

Spring is also currently providing some awesome solutions not provided at all by JavaEE:

  • Spring Data (Really nice especially for the NoSQL world)
  • Spring Social (Woops… JSR-357 has recently been rejected…)
  • Spring Mobile

Some of them are in the plan of the next versions of Java EE (yay, we will have it in 3 years!) while others have still not been taken into consideration or have been rejected.

Integration Testing

One of the common argument for Java is that you don’t have to use mocks,  you can do in-container testing thanks to Arquillian. I am definitely in favor of in-container testing instead of mocks and Arquillian is a great tool. Anyway, Arquillian is nice for Java EE but it is not Java EE! There is no standards for that and so you depend on a single vendor, JBoss (redhat), which makes the “It is standard” argument pointless. Then it is not impossible to test spring with Arquillian… At least, even if it is not perfect, Spring has the merit to provide something by its own…

Conclusion

I have not focused my article on the enhancement provided by the Java EE platform nor on the different features implemented by each, that was not my goal. I still believe that Java EE is a really good product and that it has finally become a serious competitor. But when I read “While Spring was revolutionary in its time [...], it really is last generation’s framework – some people are even calling it legacy” that really annoys me. How can we say that?! Maybe just to do a buzz… and it works!

Posted in Spring | Tagged , | 3 Comments
Jul 08

JRebel and Gradle Integration

I have started to use JRebel and believe me, that’s a great tool! To configure it, you have to specify the absolute path of your project directories in the configuration file. When working in a team, it is always problematic to have a configuration file with absolute path in version control.

A plugin for maven exists to generate the rebel.xml files but for gradle, nope. Sadly it seems that Zeroturnaround has removed their gradle plugin from their repository.

Hopefully generating a xml file in groovy is a piece of cake. So I have done my own code to generate the rebel.xml file before building the war file.

task generateRebel << {
    def rebelFile = sourceSets.main.output.classesDir.absolutePath + '/rebel.xml'

    def srcWebApp = project.webAppDir.absolutePath
    def writer = new FileWriter(rebelFile)
    new MarkupBuilder(writer).application() {
        classpath{
            dir( name:sourceSets.main.output.classesDir.absolutePath )
        }
        web{
            link(target:'/'){
                dir(name:srcWebApp)
            }
        }
    }
}
war.dependsOn generateRebel

That’s it! Your rebel.xml will be generated on the fly, you just need to activate JRebel on the server!

Posted in Uncategorized | Tagged , | Leave a comment
Jun 29

Implementing a default toString method with AspectJ

Overview

AspectJ has some real powerful usages. One is to inject a method inside a set of classes. Most of the time, I implement the toString() method using the useful reflectionToString method of Apache common.

So, I have decided to define an Aspect that will add the toString method to all my classes.

The Aspect

public aspect ToString {
    private interface ReflectiveToString {}
    declare parents : com.invalidcodeexception.experiment.aspectj.* implements ReflectiveToString;

    public String ReflectiveToString.toString(){
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}

With AspectJ you cannot define a method implemtation for a set of classes directly, but you can do it for an interface, and so all inherited classes! Therefore, I first declare the ReflectiveToString interface; Then, I make all classes that I want to modify inheriting this interface; Finally, I add the toString implementation to all classes implementing ReflectiveToString.
That’s it! Now, all classes inside the package com.invalidcodeexception.experiment.aspectj and its sub-package will have a nice implementation of toString!

Test

package com.invalidcodeexception.experiment.aspectj;

public class MyEntity {
    private String name;

    public MyEntity(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        MyEntity e = new MyEntity("hello");
        System.out.println("print entity : " + e.toString());
    }
}}

print entity : MyEntity[name=hello]

Inheritance and overriding

The interesting point is that, you can override the toString methods in your classes. So the aspect acts like a default implementation.

The only limitation is when one of your classes extends a class not concerned by your aspects which already define toString. You are facing a kind of multiple inheritance problem. In this case you will end with a “inter-type declaration” compilation error. Your best option is to simply define the toString method in the concerned class and calling super.toString()

Posted in AOP | Tagged , | 2 Comments
Jun 21

Java volatile keyword explained by example

Overview

volatile is probably the less known/understood/documented keyword in Java.
I have recently read an article on one of my favourite blog about the volatile keyword. The author shows a piece of code where the volatile keyword seems to have an influence. This example was not easy to understand and the role of the volatile keyword on the behaviour of the JVM was not really defined. So I have decided to browse the web to find a better code example for the volatile keyword. After one hour, nothing! Only wrong examples, articles comparing volatile with synchronized and other confused examples where the author seems as lost as the reader…

Basic Example

The following show a basic example where volatile is required

public class VolatileTest {

    private static volatile int MY_INT = 0;

    public static void main(String[] args) throws InterruptedException
    {
        new ChangeListener().start();
        System.out.println("Waiting two seconds so the JIT will probably optimize ChangeListener");
        Thread.sleep(2000);

        new ChangeMaker().start();
    }

    static class ChangeListener extends Thread {
        @Override
        public void run() {
            int local_value = MY_INT;
            while ( local_value < 5){
                if( local_value!= MY_INT){
                    System.out.println("Got Change for MY_INT : "+ MY_INT);
                     local_value= MY_INT;
                }
            }
        }
    }

    static class ChangeMaker extends Thread{
        @Override
        public void run() {

            int local_value = MY_INT;
            while (MY_INT <5){
                System.out.println("Incrementing MY_INT to " + (local_value + 1));
                MY_INT = ++local_value;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
    }
}

With the volatile keyword the output is :
Incrementing MY_INT to 1
Got Change for MY_INT : 1
Incrementing MY_INT to 2
Got Change for MY_INT : 2
Incrementing MY_INT to 3
Got Change for MY_INT : 3
Incrementing MY_INT to 4
Got Change for MY_INT : 4
Incrementing MY_INT to 5
Got Change for MY_INT : 5

Without the volatile keyword the output is :
Incrementing MY_INT to 1
Incrementing MY_INT to 2
Incrementing MY_INT to 3
Incrementing MY_INT to 4
Incrementing MY_INT to 5
.....And the change listener loop infinitely...

Explanation

So what happens? Each thread has its own stack, and so its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables in its own memory. The volatile keyword is used to say to the jvm “Warning, this variable may be modified in an other Thread”. Without this keyword the JVM is free to make some optimizations, like never refreshing those local copies in some threads. The volatile force the thread to update the original variable for each variable. The volatile keyword could be used on every kind of variable, either primitive or objects! Maybe the subject of another article, more detailed…

Never used volatile and never met this problem…

Like all threads issues, it happens under specials circumstances. Really special for this one… My example has big chances to show mainly because the ChangeListener thread is busy, thanks to the loop, and the JVM consider that this thread has no time for updating the local variables. Executing some synchronized methods or adding an other variable which is volatile (or even executing some simple lines of code) could modify the JVM behavior and “correct” this problem…

Should I do a big refactor to identify all variables who needs volatile?

Be pragmatic! If you think your project needs it, do it. I think that the essential is to be aware of that, to know what is the goal of each keyword of the java language in order to take the good decisions.

Please find my source code on my github repository

Posted in Java Core | Tagged | 21 Comments