|
| 1 | +import java.lang.LazyConstant; |
| 2 | +import java.util.logging.Logger; |
| 3 | + |
| 4 | +public class LazyConstantsDemo { |
| 5 | + |
| 6 | + private static final LazyConstant<Logger> LOGGER = |
| 7 | + LazyConstant.of(() -> { |
| 8 | + System.out.println("Creating Logger only once..."); |
| 9 | + return Logger.getLogger(LazyConstantsDemo.class.getName()); |
| 10 | + }); |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + |
| 14 | + System.out.println("Program started"); |
| 15 | + |
| 16 | + System.out.println("\nFirst call:"); |
| 17 | + useLogger(); |
| 18 | + |
| 19 | + System.out.println("\nSecond call:"); |
| 20 | + useLogger(); |
| 21 | + } |
| 22 | + |
| 23 | + static void useLogger() { |
| 24 | + LOGGER.get().info("Lazy constant is being used"); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +/* |
| 29 | +What changed: Previous vs New |
| 30 | +
|
| 31 | +Previous Java style: |
| 32 | +- Usually we used eager initialization with final fields |
| 33 | +- Object created when class/object loads |
| 34 | +- Resource may be created even if never used |
| 35 | +
|
| 36 | +Example: |
| 37 | +private static final Logger LOGGER = |
| 38 | + Logger.getLogger(LazyConstantsDemo.class.getName()); |
| 39 | +
|
| 40 | +New Java 26 style: |
| 41 | +- Uses LazyConstant |
| 42 | +- Value is created only when needed |
| 43 | +- After initialization, value behaves like a constant |
| 44 | +
|
| 45 | +Why the new approach is better: |
| 46 | +- Delays object creation until first use |
| 47 | +- Useful for expensive objects |
| 48 | +- Still gets JVM constant-like optimizations |
| 49 | +- Cleaner than manual lazy initialization |
| 50 | +
|
| 51 | +Pros: |
| 52 | +1. Better startup behavior |
| 53 | + - Expensive object is not created immediately |
| 54 | +
|
| 55 | +2. Cleaner code |
| 56 | + - No manual null checks or synchronized blocks |
| 57 | +
|
| 58 | +3. Thread-safe |
| 59 | + - Value is set at most once |
| 60 | +
|
| 61 | +4. Optimized by JVM |
| 62 | + - Lazy constants are treated as true constants |
| 63 | +
|
| 64 | +Cons: |
| 65 | +1. Preview feature |
| 66 | + - LazyConstant is still a preview API in Java 26 |
| 67 | +
|
| 68 | +2. New API |
| 69 | + - Developers need to learn it |
| 70 | +
|
| 71 | +3. Not needed everywhere |
| 72 | + - Simple objects may not need lazy initialization |
| 73 | +
|
| 74 | +Best use case: |
| 75 | +- Logger creation |
| 76 | +- Heavy configuration objects |
| 77 | +- Expensive services initialized only when required |
| 78 | +
|
| 79 | +Compile and run: |
| 80 | +javac --enable-preview --release 26 LazyConstantsDemo.java |
| 81 | +java --enable-preview LazyConstantsDemo |
| 82 | +*/ |
0 commit comments