Lazy initialization of a field may be useful when both of these conditions are true :
- the field is particularly expensive to create
- the field has an optional character, in the sense that it may or may not be of interest to the caller
As usual, the size of the performance gain is highly dependent on the problem, and in many cases may not be significant. As with any optimization, this technique should be used only if there is a clear and significant benefit. In particular, if the creation of the object is not particularly expensive, then using lazy initialization is very likely of dubious benefit.
To avoid a NullPointerException, a class must self-encapsulate fields that have lazy initialization. That is, a class cannot refer directly to such fields, but must access them through a method.
The hashCode method of an immutable Model Object is a common candidate for lazy initialization. In this case, the goal is to avoid the cost of recalculating the same number over and over again (see example below).
Example 1
import java.util.*; public final class Athlete { public Athlete(int aId){ //Fetch athlete info from database, but do NOT //assign a value to the fAwards field //Here is a toy implementation: fId = aId; fName = "Roger Bannister"; //fAwards is not set here! } //..other methods elided /** * Lazy initialization is used here; this assumes that awards * may not always be of interest to the caller, * and that for some reason it is particularly expensive to * fetch the List of Awards. */ public List getAwards(){ if ( fAwards == null ) { //the fAwards field has not yet been populated //Typically, one would fetch from database using fId //fAwards = dao.getAthleteAwards(fId); //Here is a toy implementation List awards = new ArrayList(); awards.add( "Gold Medal 2006" ); awards.add( "Bronze Medal 1998" ); fAwards = awards; } return fAwards; } /** * This style applies only if the object is immutable. * * Another alternative is to calculate the hashCode once, when the * object is initially constructed (again, applies only when object is * immutable). */ @Override public int hashCode(){ if ( fHashCode == 0 ) { fHashCode = HashCodeUtil.SEED; fHashCode = HashCodeUtil.hash(fHashCode, fId); fHashCode = HashCodeUtil.hash(fHashCode, fName); fHashCode = HashCodeUtil.hash(fHashCode, fAwards); } return fHashCode; } // PRIVATE // private int fId; private String fName; //Awards may not be of interest to user of this class private List fAwards; private int fHashCode; }
Example 2
Lazy initialization is particularly useful for GUIs which take a long time to construct.
There are several policies for GUI construction which a design may follow :
- always build - construct the window many times, whenever it is demanded, and do not cache the result.
- first-request build - construct the window once, when first requested. Cache the result for any further requests, should they occur.
- background build - construct the window once, in a low priority worker thread, when the system is initialized. Cache the result for any requests, should they occur.
package hirondelle.stocks.preferences; import java.awt.event.*; import javax.swing.*; import java.util.*; import java.util.logging.*; import hirondelle.stocks.util.Args; import hirondelle.stocks.util.ui.StandardEditor; import hirondelle.stocks.util.ui.UiUtil; import hirondelle.stocks.preferences.PreferencesEditor; import hirondelle.stocks.util.Util; /** * Present dialog to allow update of user preferences. * * <P>Related preferences are grouped together and placed in * a single pane of a <tt>JTabbedPane</tt>, which corresponds to an * implementation of {@link PreferencesEditor}. Values are pre-populated with * current values for preferences. * *<P>Most preferences have default values. If so, a * <tt>Restore Defaults</tt> button is provided for that set of related * preferences. * *<P>Preferences are not changed until the <tt>OK</tt> button is pressed. * Exception: the logging preferences take effect immediately, without the need * for hitting <tt>OK</tt>. */ public final class EditUserPreferencesAction extends AbstractAction { /** * Constructor. * * @param aFrame parent window to which this dialog is attached. * @param aPrefEditors contains implementations of {@link PreferencesEditor}, * each of which is placed in a pane of a <tt>JTabbedPane</tt>. */ public EditUserPreferencesAction (JFrame aFrame, List<PreferencesEditor> aPrefEditors) { super("Preferences...", UiUtil.getEmptyIcon()); Args.checkForNull(aFrame); Args.checkForNull(aPrefEditors); fFrame = aFrame; putValue(SHORT_DESCRIPTION, "Update user preferences"); putValue(LONG_DESCRIPTION, "Allows user input of preferences."); putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_P) ); fPrefEditors = aPrefEditors; } /** Display the user preferences dialog. */ public void actionPerformed(ActionEvent event) { fLogger.info("Showing user preferences dialog."); //lazy construction: fEditor is created only once, when this action //is explicitly invoked if ( fEditor == null ) { fEditor = new Editor("Edit Preferences", fFrame); } fEditor.showDialog(); } // PRIVATE // private JFrame fFrame; private java.util.List<PreferencesEditor> fPrefEditors; private static final Logger fLogger = Util.getLogger(EditUserPreferencesAction.class); /** * Specifying this as a field allows for "lazy" creation and use of the GUI, which is * of particular importance for a preferences dialog, since they are usually heavyweight, * and have a large number of components. */ private Editor fEditor; /** * Return GUI for editing all preferences, pre-populated with current * values. */ private JComponent getPrefEditors(){ JTabbedPane content = new JTabbedPane(); content.setTabPlacement(JTabbedPane.LEFT); int idx = 0; for(PreferencesEditor prefEditor: fPrefEditors) { JComponent editorGui = prefEditor.getUI(); editorGui.setBorder(UiUtil.getStandardBorder()); content.addTab(prefEditor.getTitle() , editorGui); content.setMnemonicAt(idx, prefEditor.getMnemonic()); ++idx; } return content; } /** Called only when the user hits the OK button. */ private void saveSettings(){ fLogger.fine("User selected OK. Updating table preferences."); for(PreferencesEditor prefEditor: fPrefEditors) { prefEditor.savePreferences(); } } /** * An example of a nested class which is nested because it is attached only * to the enclosing class, and it cannot act as superclass since multiple * inheritance of implementation is not possible. * * The implementation of this nested class is kept short by calling methods * of the enclosing class. */ private final class Editor extends StandardEditor { Editor(String aTitle, JFrame aParent){ super(aTitle, aParent, StandardEditor.CloseAction.HIDE); } public JComponent getEditorUI () { JPanel content = new JPanel(); content.setLayout( new BoxLayout(content, BoxLayout.Y_AXIS) ); content.add( getPrefEditors() ); //content.setMinimumSize(new Dimension(300,300) ); return content; } public void okAction() { saveSettings(); dispose(); } } }
|
|