How to clear ResourceBundle cache

Ben George picture Ben George · Mar 22, 2012 · Viewed 13.1k times · Source

This is a webapp running on Tomcat, using Guice. According to the docs we should be able to call ResourceBundle.clearCache(); to clear the ResourceBundle cache and presumably get the latest from the bundle property files.

We have also tried the following:

Class klass = ResourceBundle.getBundle("my.bundle").getClass().getSuperclass();
Field field = klass.getDeclaredField("cacheList");
field.setAccessible(true);
ConcurrentHashMap cache = (ConcurrentHashMap) field.get(null);
cache.clear(); // If i debug here I can see the cache is now empty!

and

ResourceBundle.clearCache(this.class.getClassLoader());

The behavior that I am expecting is:

  1. Start up tomcat and hit a page and it says 'Hello World'
  2. Change the properties file containing 'Hello World' to 'Goodbye Earth'
  3. Clear the cache using a servlet
  4. Hit the page and expect to see 'Goodbye Earth'

So question is, how is ResourceBundle.clearCache() actually working ? And is there some generic file cache we need to clear also ?

Answer

Devrim picture Devrim · Nov 3, 2014

This worked for me:

ResourceBundle.clearCache();
ResourceBundle resourceBundle= ResourceBundle.getBundle("YourBundlePropertiesFile");
String value = resourceBundle.getString("your_resource_bundle_key");

Notes:

  1. ResourceBundle.clearCache() is added at Java 1.6
  2. Do not use a static resourceBundle property, use ResourceBundle.getBundle() method after invoking clearCache() method.