public interface Lazy<T>
Lazy computes its value on
the first call to get() and remembers that same value for all
subsequent calls to get().
All implementations are expected to be thread-safe and compute their value at most once.
@Module
final class CounterModule {
int next = 100;
@Provides Integer provideInteger() {
System.out.println("computing...");
return next++;
}
}
final class DirectCounter {
@Inject Integer value;
void print() {
System.out.println("printing...");
System.out.println(value);
System.out.println(value);
System.out.println(value);
}
}
Injecting a DirectCounter and invoking print() reveals that
the value is computed before it is required:
computing...
printing...
100
100
100
Provider.get() 3 times and prints each result:
final class ProviderCounter {
@Inject Provider<Integer> provider;
void print() {
System.out.println("printing...");
System.out.println(provider.get());
System.out.println(provider.get());
System.out.println(provider.get());
}
}
Injecting a ProviderCounter and invoking print() shows that
a new value is computed each time Provider.get() is used:
printing...
computing...
100
computing...
101
computing...
102
Lazy for the integer. Like the provider above,
it calls Lazy.get() 3 times and prints each result:
final class LazyCounter {
@Inject Lazy<Integer> lazy;
void print() {
System.out.println("printing...");
System.out.println(lazy.get());
System.out.println(lazy.get());
System.out.println(lazy.get());
}
}
Injecting a LazyCounter and invoking print() shows that a new
value is computed immediately before it is needed. The same value is returned
for all subsequent uses:
printing...
computing...
100
100
100
Lazy is independent, and remembers its value
in isolation of other Lazy instances. In this example, two LazyCounter objects are created and print() is called on each:
final class LazyCounters {
@Inject LazyCounter counter1;
@Inject LazyCounter counter2;
void print() {
counter1.print();
counter2.print();
}
}
The output demonstrates that each Lazy works independently:
printing...
computing...
100
100
100
printing...
computing...
101
101
101
Use @Singleton to share one instance among all
clients, and Lazy for lazy computation in a single client.| Modifier and Type | Method and Description |
|---|---|
T |
get()
Return the underlying value, computing the value if necessary.
|
T get()
Lazy instance will return the same result.