What is lazy initialization?
Best Practices and Examples
Example:
private final FieldType field = computeFieldValue();
Use normal initialization for most fields, unless otherwise required.
Example:
private FieldType field; synchronized FieldType getField() { if (field == null) { field = computeFieldValue(); } return field; }
3. Carrier Class Practice (For Static Fields)
Example:
private static class FieldHolder { static final FieldType field = computeFieldValue(); } static FieldType getField() { return FieldHolder.field; }
Advantage: Initializes the class only when the field is accessed, with minimal cost after initialization.
4. Double Check Practice (For Instance Fields)
Example:
private volatile FieldType field; FieldType getField() { FieldType result = field; if (result == null) { // Primeira verificação (sem bloqueio) synchronized (this) { result = field; if (result == null) { // Segunda verificação (com bloqueio) field = result = computeFieldValue(); } } } return result; }
5. Single Check Practice (Repeated Initialization Allowed)
Example
private volatile FieldType field; FieldType getField() { if (field == null) { // Verificação única field = computeFieldValue(); } return field; }
6. Bold Single Check Practice
Example:
private FieldType field; FieldType getField() { if (field == null) { // Sem volatile field = computeFieldValue(); } return field; }
General Considerations
Trade-offs:
Multithread Synchronization:
Preferred Use:
Final Summary
The above is the detailed content of Item Use lazy initialization sparingly. For more information, please follow other related articles on the PHP Chinese website!