From 8c7d863828e0bf4b9045075ff3ccd386993dfbb5 Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Fri, 10 Jul 2015 22:01:30 -0400 Subject: lazy: Fix Lazy when a provider returns null. --- .../src/main/java/com/tavianator/sangria/lazy/Lazy.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'sangria-lazy/src/main') diff --git a/sangria-lazy/src/main/java/com/tavianator/sangria/lazy/Lazy.java b/sangria-lazy/src/main/java/com/tavianator/sangria/lazy/Lazy.java index adf531c..ee42a2f 100644 --- a/sangria-lazy/src/main/java/com/tavianator/sangria/lazy/Lazy.java +++ b/sangria-lazy/src/main/java/com/tavianator/sangria/lazy/Lazy.java @@ -56,8 +56,10 @@ import javax.inject.Provider; * @since 1.2 */ public final class Lazy { + private static final Object SENTINEL = new Object(); + private final Provider provider; - private volatile T instance = null; + private volatile Object instance = SENTINEL; @Inject Lazy(Provider provider) { @@ -67,15 +69,16 @@ public final class Lazy { /** * @return A lazily-produced value of type {@code T}. */ + @SuppressWarnings("unchecked") public T get() { // Double-checked locking - if (instance == null) { + if (instance == SENTINEL) { synchronized (this) { - if (instance == null) { + if (instance == SENTINEL) { instance = provider.get(); } } } - return instance; + return (T) instance; } } -- cgit v1.2.3