Monday, December 10, 2007

Resource Bundle Surprise

Not many people knows but Resource Bundle which used to read properties files actually cache the property file content in memory, those changing the content of the properties file at run time wouldn't influence on the application.

The question is how to cause the application to reload the properties file without the need to restart the application server?

The answer is a bit tricky since the resource bundle doesn't expose an API to refresh the cache of the properties file, there is a need to write an MBean which would invoke by the JMX console and this MBean would refresh the properties file content, here is the code for that:

Class aClass = ResourceBundle.getBundle(PROPERTIES_FILE).getClass().getSuperclass();
Field field = aClass.getDeclaredField("cacheList");
field.setAccessible(true);
sun.misc.SoftCache cache = (sun.misc.SoftCache) field.get(null);
cache.clear();


First we get the class of the resource bundle, then we change the cacheList field from private to public (Yes it is possible to change using reflection private memebers to public members) and then get invoke clear method on the cache field.

4 comments:

Anonymous said...

hello,
described trick doesn't work for me (and as I many hours googled for this problem - I'm not alone).
Yes, cache is cleared, but then it restored somehow and from somewhere. So bundles don't do refresh.

Have You any ideas about what is reason for?

Anonymous said...

In java 6 this can't trick done, do you user Java 6?

Another solution for you is not using Resource Bundle for reading the properties file and instead load this properties file by your own mechanism, it is very simple to implement such think

Anonymous said...

I use Java 5.
And resource bundle there is used on jsf&facelet page. So I've write my own < f:loadBundle ..>. I glad You says it's simple, it makes me more cheerful. Anyway strange it doesn't work as described in many articles,blogs,forums.

Anonymous said...

Hi,
I'm using java6 and this is the code which we are using but it is throwing nosuchfieldexception because of cacheList.
Is there any alternative for this ?
I'm getting a null.

Links

 
RSS Feeds Submission Directory