Saturday, March 13, 2010

Don’t be smart. Never implement a resource bundle cache!

by Eduardo Rodrigues

Well, first of all, I’d like to apologize for almost 1 year of complete silence. Since I’ve transferred from Oracle Consulting in Brazil to product development at the HQ in California, it’s been a little bit crazy here. It took a while for me to adjust and adapt to this completely new environment. But I certainly can’t complain, cause it’s been AWESOME! Besides, I'm of the opinion that, if there’s nothing really interesting to say, then it’s better to keep quiet :)

Having said that, today I want to share an interesting experience I had recently here at work. First I’ll try to summarize the story to provide some context.

The Problem

A few months ago, a huge transition happened in Oracle’s internal IT production environment when 100% of its employees (something around 80K users) were migrated from old OCS (Oracle Collaboration Suite) 10g to Oracle’s next generation enterprise collaboration solution: Oracle Beehive. Needless to say, the expectations were big and we were all naturally tense, waiting to see how the system would behave.

Within a week with the system up and running, some issues related to the component I work on (open source Zimbra x Oracle Beehive integration) started to pop up. Among those, the most serious was a mysterious memory leak, which had never been detected before during any stress test or even after more than a year of production, but was now causing containers in the mid-tier cluster to crash after a certain period.

After a couple days of heap dump and log files analysis, we discovered that the culprit were 2 different resource caches maintained by 2 different components in Zimbra’s servlet layer, both related to its internationalization capabilities. In summary, one was a skin cache and the other was a resource bundle cache.

Once we dove into Zimbra’s source code, we quickly realized we were not really facing a memory leak per se but an implementation which clearly underestimated the explosive growth in memory consumption that a worldwide deployment like ours has a huge potential to trigger.

Both caches were simply HashMap objects and, ironically, their keys were actually the key to our problem. The map keys were defined as a combination that included client’s locale, user agent and, in the case of the skins cache, the skin name was also included. Well… you can probably imagine how many different combinations of these elements are possible within a worldwide system deployment, right? Absolutely! In our case, each HashMap would quickly reach 200MB. Of course, consuming 400MB out of 1GB of configured heap space with only 2 objects is not very economic (to say the least).

So, OK. Great! We found our root cause (which is awesome enough in this kind of hard-to-analyze-production-only bugs). But now comes the harder part: how can we fix it?!

The Solution

First of all, it’s very important to keep this very important aspect in mind: we were dealing with a source code that wasn’t ours, therefore, keeping changes as minimal as possible was always crucial.

One thing we noticed right away was the fact that we were most likely creating multiple entries in both maps that ended up containing identical copies of a same skin or resource bundle content. That’s because our system only supported 15 distinct locales, which means, every unsupported client locale would fallback to one of the supported locales, ultimately, the default English locale. However, the map key would still be composed with the client’s locale, thus creating a new map entry, and even worse, mapping to a new copy of the fallback locale. Yes, locales and skins that had already been loaded and processed, were constantly being reloaded, reprocessed and added to the caches.

So, our first approach was to perform a small intervention with the only intention to prevent any unsupported client locale from originating a new entry in those maps. Ideally, we would want to change the maps’ key composition but we were not very comfortable with this idea, mainly because we were not sure we fully understood all the consequences of that, and fix the problem causing another was not an option.

Unfortunately, days after patching the system, our containers were crashing with OutOfMemory exceptions again. As we discovered – the hardest way – simply containing the variation of the locale component in the maps’ key composition was enough to slow down the heap consumption but not enough to avoid the OOM crashes.

Now it was time to put our “fears” aside and dig deeper. And we decided to dig in two simultaneous fronts: the skin cache and the resource bundle cache. In this post, I’ll only talk about the resource bundle front leaving the skin cache front to a next post.

When I say “resource bundle”, I’m actually referring to Java’s java.util.ResourceBundle, more specifically its subclass java.util.PropertyResourceBundle. With that in mind, 2 strange things caught my attention while looking carefully into the heap dumps:

  1. Each ResourceBundle instance had a “parent” attribute pointing to its next fallback locale and so on, until the ultimate fallback, the default locale. This means that each loaded resource bundle could actually encapsulate other 2 bundles.
  2. There were multiple ResourceBundle instances (each one with a different memory address) for 1 same locale.

So, number 1 made me realize that the memory consumption issue was even worse than I thought. But number 2 made no sense at all. Why have a cache that is only stocking objects but is not able to reuse existing ones? So I decided to take a look at the source code of class java.util.ResourceBundle in JDK 5.0. The Javadoc says:

“Implementations of getBundle may cache instantiated resource bundles and return the same resource bundle instance multiple times.”

Well, turns out Sun’s implementation (the one we use) DOES CACHE instantiated resource bundles. Even better, it uses a soft cache, which means all content is stored as soft references, granting the garbage collector the permission to discard one or more of its entries if it decides it needs to free up more heap space. Problem solved! – I thought. I just needed to completely remove the unnecessary resource bundle cache from Zimbra’s code ant let it take advantage of the JVM’s internal soft cache. And that’s exactly what I tried. But, of course, it wouldn’t be that easy…

Since at this point I already knew exactly how to simulate the root cause of our problem, I started debugging my modified code and I was amazed when I saw that the internal JVM’s cache was also stocking up multiple copies of bundles for identical locales. The good thing was that now I could understand what was causing #2 above. But why?! The only logical conclusion was, again, to blame the cache’s key composition.

The JVM’s resource bundle cache also uses a key, which is composed by the bundle’s name + the corresponding java.util.Locale instance + a weak reference to the class loader used to load the bundle. But then, how come a second attempt to load a resource bundle named “/zimbra/msg/ZmMsg_en_us.properties”, corresponding to en_us locale and using the very same class loader was not hitting the cache?

After a couple hours thinking I was loosing my mind, I finally noticed that, in fact, each time a new load attempt was made, the class loader instance, although of the same type, was never the same. And I also noticed that its type was actually an extended class loader implemented by inner-class com.zimbra.webClient.servlet.JspServlet$ResourceLoader. When I checked that code, I immediately realized that class com.zimbra.webClient.servlet.JspServlet, which itself is an extension of the real JspServlet being used in the container, was overriding method service() and creating a new private instance of custom class loader ResourceLoader and forcefully replacing the current thread’s context class loader with this custom one, which was then utilized to load the resource bundles.

My first attempt to solve this mess was to make the custom class loader also override methods hashCode() and equals(Object) so they would actually proxy the parent class loader (which was always the original one that was replaced in method service()). Since the web application’s class loader instance would always be the same during the application’s entire life cycle, both hashCode and equals for the custom loader would consistently return the same results at all times, thus causing the composed keys to match and cached bundles to be reused instead of reloaded and re-cached. And I was wrong once again.

Turns out, as strange as it may look at first sight, when the JVM’s resource bundle cache tries to match keys in its soft cache, instead of calling the traditional equals() to compare the class loader instances, it simply uses the “==” operator, which simply compares their memory addresses. Actually, if we think more about it, we start to understand why they implemented this way. Class loaders are never expected to be constantly instantiated, over and over again, during the life cycle of any application, so why make an overhead method call to equals()?

Finally, now I knew for sure what was the definitive solution. I just needed to transform the private instances of ResourceLoader into a singleton, keeping all the original logic. Bingo! Now I could see the internal bundle cache being hit as it should be. Problem solved, at last!

At the end, after having completely removed the custom resource bundle cache implemented in Zimbra’s servlet layer and performed the necessary changes to make Zimbra take full and proper advantage of the built-in bundle cache offered by the JVM, instead of wasting a lot of time and memory reloading and storing hundreds of instances of resource bundles, mostly multiple copies of identical bundles, I could now confirm that despite all different client locales coming in clients' requests, the JVM’s bundle cache was holding no more than those corresponding to the 15 supported locales. With that, we had finally fixed the memory burning issue for good.

Conclusion

As this article’s title suggests, don’t try to be smarter than the JVM itself without first checking whether it’s doing it’s job well enough or not. Always do carefully read the Javadocs and, if needed, check your JVM’s source code to be sure about its behavior.

And remember…. never implement a resource bundle cache in your application (at least if you’re using Sun’s JVM) and be very careful when implementing and using your own custom class loaders too.

That’s all for now and…
Keep reading!

Thursday, April 9, 2009

Our first official book review in on its way...

by Eduardo Rodrigues

Great news!

We have been contacted (surprisingly) by Packt Publishing a few days ago and asked if we would be interested in read one of their new books and then publish an independent review here in the blog. We were very honored and flattered with the offer, so we obviously accepted it.

The book is "Processing XML documents with Oracle JDeveloper 11g" by Deepak Vohra.

One good thing that immediately caught my attention as soon as the book arrived today was seeing the name "Frank Nimphius" in the list of reviewers. This is certainly a good sign :)

Anyway, Fabio and I already have the book and we'll both read it and then compile our comments in a 4-hand post to come. We hope it wont take too long (and also hope this will be just the first of many other book reviews to come).

Cheers and keep reading!

Tuesday, March 24, 2009

Java and the Timezones

by Fábio Souza

Timezone, when using Java, can be something tricky. You can get surprised when you change your OS timezone (something common to countries with DST) and it doesn't take any effect on your Java programs. What does Sun have to say about that? It can be found at their FAQ:

Do my operating system's timezone patches fix the Java platform's timezone data?

No. The Java SE platform's timezone data is not read from the local or host operating system. The Java SE platform maintains a private repository of timezone data in locally installed files (.../jre/lib/zi) as part of the Java Runtime Environment (JRE) software. Applying whatever operating system timezone patches (for example Solaris OS, Linux, Windows) will have no effect on the accuracy of the Java SE platform's timezone data.

Sun recommends you to maintain all JVM up to date to avoid Timezone problems. To specific cases where a Timezone update is needed, they provide a tool called TZUpdater. TZUpdater is a JAR that contains timezone informations provided by Olson Timezone Database. To update the JVM's timezone you need to execute TZUpdater's most recent version like this:

java -jar tzupdater.jar -u (don't forget to check if you have read/write access to Java's directory structure)

We are ok about Sun's JVM... But the solution is the same to all JVMs? Not really =), but it is very similar to IBM JVM and Oracle JRockit. In all cases we either have to download a program and execute it to update the installed JVM or wait for the next JVM update release.

Here are some useful links:

Sun:

IBM (thanks to my friend and co-worker Frederico Hakamine):

Oracle:

Tuesday, February 10, 2009

Web Component Developer Exam (SCWCD) for JEE 5

by Wellington Carvalho

I hope my feedback can help those who want to prepare for The Web Component Developer exam (SCWCD) for JEE 5. I will use the same structure of an older post that Fabio Souza wrote to pass his own experience with SCJP 5 exams.

Main reading resource

Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam

The first edition of the book deals with J2EE 1.4 spec, but the changes in JEE 5 were
most related to EJB 3, so I think you won’t have troubles with the exam! But if you want, the second edition of the Head First Servlets and JSP is prepared for JEE 5 and you can find it here: http://oreilly.com/catalog/9780596516680/?CMP=AFC-ak_book&ATT=Head+First+Servlets+and+JSP

Main resources for exercises

I used an application similar to Whizlabz named Enthuware. Enthuware is an exercise tool with many tests that covers all the objectives mentioned by Sun. The exercises of Enthuware are very similar to the exam, and you have good explanations, no matter the answer is right or wrong.

In order to get a better performance in your study you should take the standard tests of Enthuware sequentially and exclusively when you have read the entire SCWCD book.
To evaluate your chapter’s knowledgement you should take the objective-wise tests only after reading the chapter. To get the full version of Enthuware you will spend around US$29,00 which is cheaper than the other: Whizlabz (US$74,95). If you fail the SCWCD exam the company guarantee your money back (must get at least 70% in the tests).

My study schedule

It took me 35 days to read all the 14 chapters and to do all the tests
and exercises of Enthuware. I spent 2 hours and a half per day to read the chapter and 1 hour to do the exercises. In the week before the exam I just took the standard tests and reviewed the material.

I think this schedule is reasonable to people that is working with JEE, however if you aren’t using JEE in your daily work you should reserve a longer study time.

The exam

In my opinion the exam is relatively easy to people that have work experience in JEE development, however you need to pay attention to every detail because the exam has good tricks hidden in the code. But don’t get scared. Most of them are covered by Enthuware.

To take this exam you must know about all the objectives listed by Sun, but with a special care on these below:

Servlet Technology Model
Expression Language (EL)
Custom Tag Library - Classic Model
JSP Standard Actions

It is important to remember that you need at least 70% to pass, but trust me (and Enthuware), if you start scoring more than 70% in the standard tests, you will pass easily.

Monday, November 24, 2008

SCJP 6 Upgrade Exam (310-056)

by Fábio Souza

Guys and girls,

I guess the best way to start this post is with my appologies. I really wanted to post it earlier, but you all know how things are =P.

It has been almost three months from when I took the SCJP 6 upgrade exam (310-056). The exam follows the same SCJP 5's (310-055) difficulty level where it's needed to pay attention to every detail. There is time enough to do everything calmly but the tricks are there like they were in SCJP 5. The "secret" is still the same: MAKE LOTS OF EXERCISES. In my case, my knowledge on 310-055 was pretty sharp and I just had to work out the new features of Java 6. Lets talk about the exam and how to go for it.

PS: To get your knowledge on 310-055 "pretty sharp", I recommend my previous post: SCJP5 and 6


Technical information:
  • Number of Questions: 48
  • Score needed: 66% (32 of 48 questions)
  • Time limit: 150 minutes

Resource material:

For those who don't have (or want to have) specific SCJP 6 material (the same of the previous post):

For those who want to buy new material:
* I've never read this book but if the quality is the same of the previous version, there is no doubt it should work.

I made an abstract to help me with the SCJP 6 content by comparing the requisites for both exams (310-055 and 310-065), and studying the Java 6 new features. Here it is:

- Ordered and Sorted comparison:

Click me

- NavigableSet and NavigableMap methods comparison:

Click me

- Other things:
  • Deque: in this interface's javadoc there is a full explanation about the different methods that can be used to add/remover an object of this queue. Be sure that you know the ones that returns an special value (generally null) or that throws an exception instead, when something goes wrong.

  • ArrayDeque: the best (fastest) way to make FIFO and LIFO queues. This is also the recommended implementation when we need a Stack.

  • LinkedList: choose this implementation when objects should be added/removed between the first and the last element.

  • java.util.Collections: there are two new methods in this class, newSetFromMap and asLifoQueue, learn them.

  • java.util.Arrays: avoid System.arraycopy, use the new methods Arrays.copyOf or Arrays.copyOfRange instead.

  • java.io.File: getFreeSpace, getTotalSpace, setExecutable, setWritable, setReadable. These are new methods to learn.

  • java.io.IOException: there are new constructors that enable exception chaining IOException(String,
    Throwable)
    and IOException(Throwable).

  • java.io.Console: this is a new class and its instance should be got using System.console. I think all of its methods are importants, take a look at the javadoc. Pay attention to the Console.readPassword, it will fill an array with the provided password, it is a good think to know how to clean this array. This is a good way: java.util.Arrays.fill(src, '\0') and this is a valid and bizarre way: java.util.Arrays.fill(src, 0, src.length, (char)0).
SCJP 6 - To do or not to do

Because the difference between Java 5 and Java 6 is very little, in my opinion, people who already have the SCJP 5 don't need to worry about SCJP 6. For those who don't have SCJP 5 or any SCJP certificate at all: DON'T DO the Java 5 exam; GO STRAIGHT to Java 6.
In my exam (just to freeze: 310-056), the Java 6 content was kind of ridiculous. Only THREE specific questions. It means (this is not an advice) I could take the SCJP 6 exam without any knowledge about its specific content. I'll tell you how it was like:
  • java.io.Console: A question about its usage. It was necessary to know how to get the Console instance and how to get typed lines.

  • java.util.NavigableSet and the implementation java.util.TreeSet: The question was about how to use them focusing the method subset.

  • Chosing the best Collection implementation: I don't remember exactly what was asked, but keep this in mind:

    • Stack or queue needed: use ArrayDeque.

    • Removing/Adding elements that might not be at the top or at the bottom: LinkedList.

    • Sorted Collection (unique elements): TreeSet.
That is all folks! Please send your comments, corrections and share your own experiences.