Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear ResourceBundle cache

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 ?

like image 686
Ben George Avatar asked Dec 16 '22 02:12

Ben George


2 Answers

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.
like image 156
Devrim Avatar answered Dec 18 '22 15:12

Devrim


I do not believe you can effect the reloading of an already created ResourceBundle instance since its internal control class has already been created. You may try this as an alternative for initializing your bundle:

ResourceBundle.getBundle("my.bundle", new ResourceBundle.Control() {
    @Override
    public long getTimeToLive(String arg0, Locale arg1) {
        return TTL_DONT_CACHE;
    }
});
like image 42
Perception Avatar answered Dec 18 '22 16:12

Perception