Singleton Application Properties

Normally we use a class to encapsulate all application related properties and apply the singleton pattern. This way, we could have a unique instance representing the collection of all application related properties. The benefit is that we could pick up any update to the properties and reflect it in the application on-the-fly.

This is not hard, as the following code snippet illustrate:

   public class AppProperties {

        private static final AppProperties INSTANCE = 
            new AppProperties(...);
        
        public static AppProperties getInstance() {
            return INSTANCE;
        }
        
        private AppProperties(...) {
        }
        
    }

All is very simple, great. But usually we read application properties from some repository, such as reading from disk file or from database. And usually we have exception to be handled within the private constructor. In such cases, that is, if the constructor throws an exception, this class is effectively failed “loading”. At this point, you have no choice but to restart the JVM in order to fix the problem.

This is pointed out in System Configuration Management, which says “Do not put any initialization work in Java class static constructs ...”. The purpose is really to avoid the restart of the JVM. But how can we do that at the same time to apply the singleton pattern? Here’s what the solution:

   public class AppProperties {

        private static AppProperties INSTANCE;
        
        public synchronized static AppProperties getInstance() {
            if (null == INSTANCE) {
                INSTANCE = new AppProperties(...);
            }
            
            return INSTANCE;
        }
        
        private AppProperties(...) {
        }
        
    }

Before you cry out the performance suffering from keyword synchronized applied to the method getInstance(), check out Double-checked locking: Clever, but broken. Personally, I would rather trade the slight performance suffering for the maintenance convenience.

No Responses
Leave a Reply

Leave it empty to submit anonymously.


Your email will never be displayed.





Close