Thursday, March 25, 2010

Interesting Behavior of the EJB Timer Service

In a recent discussion in the CEJUG technical discussion list, we figured out an interesting behavior of the EJB Timer Service that is very important to know when implementing a time service.

First, let me contextualize EJB Timer Service and some situations where it could be useful. EJB Time Service is an interesting feature of the EJB Specification that allows routines to be executed in a certain time (24 hours from now or 01/04/2010 at 23:35) or in a certain frequency of time (every 12 hours or every day at 02:00). The schedule of routines is very appropriate to perform automatic maintenance tasks such as cleaning temporary data, generating complex reports, sending alert messages, etc. Timers are also useful to efficiently use computational resources when systems are in idle mode. A system architect should have a good understanding of this feature to optimize the implementation of corporate solutions, where a lot of data are processed in batch. You can learn more about EJB Timer Service in the book EJB 3 in Action.

To understand this particular behavior, consider a routine scheduled to execute every 2 hours. What would happen with the next scheduled execution if the routine spends more than 2 hours to finish? It's important to estimate well the interval between executions to avoid situations like this. However, if for some reason the routine didn't finish its execution before the next schedule, then it is important to understand the consequences of this scenario.

We could observe that, if the current execution lasts longer than the configured interval, then the next execution won't happen. The schedule will be back to normal only when the current execution finishes. The figure below illustrates this behavior.


The timer process P3 was expected to execute at T3, but it didn't because P2 execution hadn't finish yet. However, P2 finishes before T4, then P4 is still expected to run on time. The stateless session bean bellow simulates this behavior:

@Stateless
public class ImageBsn implements ImageLocal {

  @Resource
  TimerService timerService;

  public void init() {
    timerService.createTimer(60 * 1000,
           60 * 1000, null);
  }

  @Timeout
  public void cleanUnusedLocations(Timer timer) {
    Calendar now = Calendar.getInstance();
    Calendar later = Calendar.getInstance();

    System.out.print("Cleaning at "+
          now.getTime());

    later.set(Calendar.MINUTE,
          now.get(Calendar.MINUTE) + 3);

    while(now.get(Calendar.MINUTE)
           < later.get(Calendar.MINUTE)) {
      now = Calendar.getInstance();
    }
    System.out.println(" and Cleaned at "+
            now.getTime());
  }
}

The code above schedules the timer to execute the timeout method every 60 seconds. Then the timeout method has a routine that keeps it running for more than 2 minutes, forcing the timer to postpone some scheduled executions. The output is:

INFO: Cleaning at Thu Mar 11 17:48:39 CET 2010
INFO: and Cleaned at Thu Mar 11 17:51:00 CET 2010
INFO: Cleaning at Thu Mar 11 17:51:39 CET 2010
INFO: and Cleaned at Thu Mar 11 17:54:00 CET 2010
INFO: Cleaning at Thu Mar 11 17:54:39 CET 2010
INFO: and Cleaned at Thu Mar 11 17:57:00 CET 2010

Therefore, you don't have to worry about implementing a multi-thread safe code in the timeout method, but you should evaluate the consequences of having one of the executions canceled.

Tuesday, March 23, 2010

Jersey and JSF Conflict caused by Netbeans

Have you noticed that JSF 2.0 has a new pre-defined directory called "resources" that is located in the web content? According to JavaServer Faces 2.0, The Complete Reference, "files in this directory are treated specially by the JSF Runtime. (...) files and directories within the /resources directory are intended to be included in other pages in the application. Content here can be images, stylesheets, and composite components.". Therefore, if your Java web application has a /resources directory with a different meaning, then you have to consider renaming it to avoid conflicts when migrating to JSF 2.0.

But there are more conflicts to deal with. I was having some relaxing time programing my JSF 2.0 application (Yasmim) on Saturday night when I decided to implement some RESTful web services. Knowing that Netbeans is like a Swiss army knife when developing JEE applications, I went into its special features to support the JAX-RS specification (JSR 311) and I could get most of the necessary configuration done automatically. However, this automation causes a conflict with the JSF application if you don't pay attention to a simple detail shown in the figure below.


The field "REST Resources Path" has the default value "/resources". This path is used in the application URL to denote the invocation of RESTful web services. For instance, in the URL "http://localhost:8080/yasmim/resources" anything after "/resources" is considered as a RESTful web service. If something after "/resources" is not correctly mapped, then a HTTP error occurs. This is actually a good practice because the key abstraction of information and data in REST is a resource. Representing it in the URL makes it clear.

However, when the application also uses the JSF 2.0 framework, this REST resource path conflicts with the JSF resources directory. As a consequence, files in the resources directory obviously are not mapped as services and won't be available for JSF pages. In practice, CSS and script files become unavailable, destroying the design and layout of the website.

To solve this conflict, we have to change the proposed resource path to another value. In my case, I'm using "/service", which is still coherent because REST is a style of web service implementation. After changing this value you have to clean and rebuild the project and redeploy the application because hot deployment in Glassfish doesn't work in this case.

Sunday, March 7, 2010

Felipe Gaúcho, You Will Be Missed

How can I write about such a delicate subject? How can I find strength and inspiration in a hard moment like this one? I would summarize this post in only one word: speechless, but the absence of words may let my thoughts and emotions incomplete. So, I decided to write as the words come to my mind, and they are not easy.

I've lost a very dear friend last Friday (March 5th, 2010). His name is Felipe Gaúcho and he had a severe heart attack. I've met Felipe in Fortaleza a long time ago. I don't remember precisely when, but one of his first attitudes with me was to invite me to become a CEJUG Leader. I immediately accepted and I started helping him on several initiatives to make the Ceará Java Community grow up. We were together in this journey until last Friday, when he passed away. His last email to me was last Sunday, our last chat was also a week ago, and his last comment on my blog was last Thursday, copying a link to his most recent post on his blog, whose content is very related with what I wrote. He is also in my list of followers, on the right, and will remain there permanently.


I believe that we always get a bit of the personality of our closest friends to incorporate in our own. Felipe was the one who taught to share. No matter what, no matter how, but no idea should be completely trapped into our minds. Writing ideas on papers is not enough. They should be transmitted to other people, who are real agents of transformation. Felipe not only transmitted his ideas but also motivated people to empower them. I have the same belief and I don't know anyone like him, thus I definitely learned it from him.

Felipe was a young man with strong positions. It took time to convince him about other point of views, but he was the only one I know that once you get to change his position you will be the first one to know that. He comes back to the topic, merges points, discusses other details and goes on the direction of a better overall solution. I believe I improved my diplomacy skills discussing technology and community with him.

He became internationally well known by his open source initiatives and his passion for the Java community.
His focus: undergraduate students.
His intention: prepare students to better face the challenges of the software industry.
His weapon: Java.
His strategy: share learned lessons from the development of open source projects.
His hope: improve the quality of undergraduate courses in Brazil.

In a situation like this, when a young life is interrupted so abruptly, we start thinking how fragile life is. In any case, death is always shocking and touching, but when a person with a closer age dies we get to think about our own existence, how life is short, and how important is every minute breathing.

Rest in peace Felipe. Your family will be constantly comforted by God and You remain in our hearts.

Friday, March 5, 2010

Definitely e-Books

I have a lot of books. Really! I love books. I buy them because I need but sometimes just for the pleasure of having them. They are interesting but they are also so beautifully organized on my bookshelf. 8) But I feel deep inside that there is something wrong with it.

What am I gonna do when the time to leave Belgium comes? I'm inclined to donate most of my books, but how? to whom? I will think about it, but you can also suggest something on the comments below. By the way, one thing that I've learned was: before buying something, consider when the time to discard it finally comes. Might it be some sort of headache for you in the future?

Besides the space and weight issues, there is also the ecological one. Books are made of paper, paper is made of cellulose, cellulose is mostly extracted from the wood, wood is synonymous of tree and trees are one of the main agents of carbon absorption, besides their role on the soil stability and humidity control.

Considering these important reasons, I decided to prioritize the acquisition of eBooks (eletronic books) because they don't have weight, don't require physical space, the unitary impact on the nature is not so relevant, and the facility to transport, browse and search information makes it worth.

Leaving aside the physical beauty, I bought some technical eBooks from O'Reilly , Apress and Packt Publishing, but there are also The Pragmatic Bookshelf and the Amazon collection for the Kindle device. Many other publishers didn't start offering eBooks yet but it is a matter of time.

Buying eBooks directly from the publisher seems to be a good deal. I bought the book Restful Java with JAX-RS for $31.99 while the printed copy costs $39.99, saving $8. But the saving amount would be even higher when considering the shipping cost. On the other hand, the Kindle store doesn't offer a big discount on the Kindle version of a book. For instance, the paper version of the book Effective Java is sold for $35.11 and the Kindle version is offered for 38.64, a surprising higher price for a digital version, but still better due to the shipping cost.

I don't have a Kindle yet, but I'm planning to buy one or any other similar product. My main concern today is to buy books that can be used in my future book reader. For that, I'm avoiding to buy books with password protection. For instance, when opening books from Apress, the Acrobat Reader asks for a password key, which is provided at the moment of the acquisition. Better not forget this key, otherwise... :D

Wednesday, March 3, 2010

You Know What? I Love My Blog

During some procrastination time that I gave to myself last night, I've spent some time exploring all posts that I have published on my blog since 2007. I'm talking about 105 posts, an average of 4 per month, which is not that much in comparison to other more popular blogs, but at least I've been quite regular over the years.

All these posts tell a lot about my research time in Belgium, thoughts, wishes, ideas, opinions, and much more. It's so amazing the amount of experiences that I've shared with you, the feedback that some of you shared with me. Yeah! For me, post's comments are the best part of this blog.

I remember how happy I was when my blog was 1 year old with almost 300 unique visitors per month. I thought: “Wow! 300 different people reading my ideas! It's a lot of people!”. I wouldn't expect that 2 years later I would have more than 1.400 unique visitors per month. Today, I'm having the same thought I had 2 years ago, since 1.400 visitors is a lot of people too ;). But I know that some of you are laughing because it is still a small number in comparison with other popular blogs, but I'm proud of each one of my visitors, mainly the 450 ones that come here more than once every month.

I wish I could share more with you here because each post represents only 20% of the full experience that I had. Actually, I don't have any profit from here, making it more like a hobby than a responsibility. I even tried putting some Google advertising on the right, but I've got only 3 clicks during these 6 months of exposure, which means absolutely nothing :D. What makes it worth is the possibility to talk to myself, to talk to you like in a restaurant and the feedback I receive when I write technical articles, mostly solving basic problems that annoy a lot of people, and I receive comments from all over the world thanking for the solution I have proposed.

Now, I would like to conclude with a attempt of poem that stays in the subconscious of this blog:
I might regret but I don't

I might regret doing things not related to my work just to solve other people's problem, but I don't because those things taught me many other things that I didn't expect to learn.

I might regret starting my research so late, but I don't because pressure is also part of the game.

I might regret allowing my love to spend several weeks far from home, but I don't because it would be very selfish, these trips are great for her carrier, and I admire her achievements.

I might regret losing contact with some friends that I've made here, but I don't because they proved to be more selfish than the friendly acceptable.

I might regret drinking and eating too much some times, but I don't because Belgium has the best beers in the world, Europe has the best cuisine and I won't be here for so long.

I might regret giving up opening a business in Europe, but I don't because what I'm planning now will help a lot more people than I was planning to help before.

Last but not least, I might regret to be too much optimistic even not archiving many wishes I had, but I don't because so many miracles have happened in my life, proving that optimism brings most of my wishes and what it doesn't bring I also gain in terms of lessons learned.
Thank you for your visit(s)!