1. In most cases, normal initialization takes precedence over deferred initialization.
Private final FieldType field = Computefieldvalue ();
2, if the use of delay optimization to break the initialization of the loop, it is necessary to use synchronous access method, because it is the simplest and clearest alternative.
Private FieldType field;synchronized FieldType GetField () { if (field = = null) { field = Computefieldvalue (); } return field;}
3. If lazy initialization is required for a static domain for performance reasons, use the lazy initialization holder class mode to ensure that the class is initialized only when it is used.
private static class fieldholder{ static final FieldType field = Computefieldvalue ();} Static FieldType GetField () { return fieldholder.field;}
When GetField is first called, the first read of Fieldholder.field causes Fieldholder to be initialized.
4, if you need to use lazy initialization for the instance domain for performance reasons, use double check mode (double-check idiom), which avoids the overhead of accessing the domain after the domain is initialized.
private volatile fieldtype field; FieldType GetField () { FieldType result = field; if (result = = null) { //first check (no locking) synchronized (this) { result = field; if (result = = null) {//second check (with locking) field = result = Computefieldvalue ();}} } return result;}
Two check the domain value, the first check is not locked, see if the domain is initialized, the second check is locked, only when the second check indicates that the domain is not initialized, the Computefieldvalue method is called to initialize the domain. Because if the domain has been initialized there will be no locks, and it is important that the domain is declared volatile.
5. If you can receive duplicate initialization, you can also consider using the single check mode (idiom)
Private volatile FieldType field;private FieldType GetField () { FieldType result = field; if (result = = null) { field = result = Computefieldvalue (); return result;}
Effective Java-----About deferred initialization