1. How would you rewrite the Singleton class to create only two, only three or only ten instances?
Insert here a HashMap
that contains the chosen number of instances.
Here is an example:
import java.io.*; import java.util.*; public class PropertiesManager implements java.io.Serializable { /** The singleton reference */ private static PropertiesSingleton config; /** Contains the configurations */ private static HashMap configurations = new HashMap(); private PropertiesManager() { } private Properties load(String configFile) throws IOException { Properties props = new Properties(); DataInputStream in = new DataInputStream( new BufferedInputStream (new FileInputStream(configFile))); props.load(in); return props; } public static PropertiesSingleton getInstance(String configurationName, String configFile) throws IOException { if (config == null) { config = new PropertiesSingleton(); } Properties p = config.load(configFile); configurations.put(configurationName, p); return config; } public static PropertiesSingleton getInstance() { if (config == null) {throw new RuntimeException( "No configuration file was provided, yet.");} return config; } public String getProperty(String configurationName, String key) { return ((Properties) configurations.get(configurationName)).getProperty(key); } }
2. It would be nice if configuration files were read automatically at every startup. How can you achieve this?
Include a Method reload (String Filename)
. This file deletes old entries of Properties-Objects
and replaces them with the newly read values.
1. Why does declaring the error statement help us much less in JSP than it would in a normal class?
The JSP is compiled into a Servlet. The declared statement refers to this servlet. You have an option to check the Servlet and then draw conclusions from your JSP.
2. Set the file path for
Log4J
to
c:/
instead of
c:\
.
Reload the context. What happens to the log file? Where do you see the error message (if at all)?
Unfortunately, the file is not created now and no error message is displayed either.
1. The
LoggerHTMLFormatter
The following statement is very important:
DateFormat dateFormatter = DateFormat.getDateInstance( DateFormat.DEFAULT, currentLocale);
A glance in the Java-API shows us this method:
static DateFormat getDateInstance() Gets the date formatter with the default formatting style for the default locale.
2. Why does the
LoggerInitiator
It is important that it’s declared as private and not so much that it is empty. If it is left out, then the class will automatically get an empty public constructor, and other classes can evade the Singleton
mechanism.