Browse Source

Synchronize lazy initialization

master
Paweł Płazieński 3 months ago
parent
commit
711d60aa8e
1 changed files with 7 additions and 3 deletions
  1. +7
    -3
      src/main/java/org/perfectable/introspection/proxy/LazyInitialization.java

+ 7
- 3
src/main/java/org/perfectable/introspection/proxy/LazyInitialization.java View File

@@ -82,7 +82,9 @@ public final class LazyInitialization {

private final Initializer<? extends T> initializer;

private transient @MonotonicNonNull T instance;
private final Object initializationMonitor = new Object();

private @MonotonicNonNull T instance;

static <T extends @NonNull Object> LazyInitializationHandler<T> create(Initializer<? extends T> initializer) {
return new LazyInitializationHandler<>(initializer);
@@ -106,8 +108,10 @@ public final class LazyInitialization {
if (EXTRACT_INSTANCE_METHOD.equals(method)) {
return () -> Optional.ofNullable(instance);
}
if (this.instance == null) {
this.instance = this.initializer.initialize();
synchronized (initializationMonitor) {
if (this.instance == null) {
this.instance = this.initializer.initialize();
}
}
return MethodInvocation.of(method, this.instance, arguments);
}


Loading…
Cancel
Save