Hot-Reload of Properties File

In this post we’ll see how to do hot-reload of properties file used by a web-application. Hot-reload is useful when we want change some property in a file without restart the application server (like JBoss). Restart an application-server (or servlet-container) means restart all the web-apps that are running under that application-server, with resulting unavailability of some sensible service. For this scope we’ll use the Java class PropertiesConfiguration in the Apache Common Configuration library. This class allow to bind a properties file to an PropertiesConfiguration Java Object through which read the single properties. Let see a very simple example in which we use the following properties file, named myprops.properties

user.name="Alex"
user.age="26"

Below we can see the source code through we going to access the file and read properties.

PropertiesConfiguration config = new PropertiesConfiguration("myprops.properties");
Strint name = config.getString("user.name");
Strint age= config.getString(key);
System.out.println("User name: " + name);
System.out.println("Age: " + age);

This is the returned values:

User name:Alex
Age: 26

Now we can see how to define a reload strategy on properties file. Once we have instantiated an PropertiesConfiguration object, we can choose a specific reload strategy between FileChangedReloadingStrategy, InvariantReloadingStrategy and ManagedReloadingStrategy as showed in the following example:

PropertiesConfiguration config = new PropertiesConfiguration("myprops.properties");
config.setReloadingStrategy(new FileChangedReloadingStrategy());
  • FileChangedReloadingStrategy: A reloading strategy that will reload the configuration every time its underlying file is changed;
  • InvariantReloadingStrategy: A strategy that never triggers a reloading;
  • ManagedReloadingStrategy: A strategy to reload configuration based on management requests. Designed for JMX management.

More detail are showed in the javadoc. As well as properties files we can use this method in the following cases too:

  • XML documents
  • Windows INI files
  • Property list files (plist)
  • JNDI
  • JDBC Datasource
  • System properties
  • Applet parameters
  • Servlet parameters

If you want to learn more retro games news, read our magazine and subscribe to our newsletter.