LazyCachedBoolean.java
/*
* Copyright 2020 Collect Utils Authors
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package net.morimekta.collect.util;
import java.util.function.BooleanSupplier;
import static java.util.Objects.requireNonNull;
/**
* Simple lazily cached value supplier, also known as a 'memoized'
* value supplier. This will lazily initialize the value on the first
* 'get' call, and assumes the value supplier will return the same
* value on every invocation, as the result should be thread-safe, but
* *may* cause multiple calls to the value supplier.
* <p>
* Calling {@link #getAsBoolean()} will on the first invocation cause the supplier
* to be called in the same thread.
*/
public final class LazyCachedBoolean implements BooleanSupplier {
/**
* Make a lazily initialized supplier for the value
* returned from the provided supplier.
*
* @param supplier The value supplier.
* @return The lazy cached supplier.
*/
public static LazyCachedBoolean lazyBoolean(BooleanSupplier supplier) {
return new LazyCachedBoolean(supplier);
}
/**
* Make a lazily initialized supplier for the value
* returned from the provided supplier.
*
* @param supplier The value supplier.
*/
public LazyCachedBoolean(BooleanSupplier supplier) {
this.supplier = requireNonNull(supplier, "supplier == null");
}
/**
* Reload the content of the cached value. This will always call the
* origin supplier.
*
* @return The cached supplier.
*/
public LazyCachedBoolean reload() {
synchronized (mutex) {
// never reset from non-null to null.
instance = supplier.getAsBoolean();
}
return this;
}
// ---- Supplier ----
@Override
public boolean getAsBoolean() {
if (instance == null) {
synchronized (mutex) {
if (instance == null) {
instance = supplier.getAsBoolean();
}
}
}
return instance;
}
// ---- Private ----
private transient volatile Boolean instance = null;
private transient final Object mutex = new Object();
private final BooleanSupplier supplier;
}