All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.robozonky.common.async.ReloadableImpl Maven / Gradle / Ivy

/*
 * Copyright 2018 The RoboZonky Project
 *
 * Licensed 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 com.github.robozonky.common.async;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;

import io.vavr.control.Either;
import io.vavr.control.Try;

final class ReloadableImpl extends AbstractReloadableImpl {

    private final AtomicReference value = new AtomicReference<>();

    public ReloadableImpl(final Supplier supplier, final UnaryOperator reloader,
                          final Consumer runWhenReloaded) {
        super(supplier, reloader, runWhenReloaded);
    }

    public ReloadableImpl(final Supplier supplier, final UnaryOperator reloader,
                          final Consumer runWhenReloaded, final Function reloadAfter) {
        super(supplier, reloader, runWhenReloaded, reloadAfter);
    }

    @Override
    public Either get() {
        if (needsReload()) { // double-checked locking to make sure the reload only happens once
            synchronized (this) {
                if (needsReload()) {
                    logger.trace("Reloading {}.", this);
                    return Try.ofSupplier(() -> getOperation().apply(value.get()))
                            .peek(v -> processRetrievedValue(v, value::set))
                            .toEither();
                }
                // otherwise fall through to retrieve the value
            }
        }
        logger.trace("Not reloading {}.", this);
        return Either.right(value.get());
    }

    @Override
    public boolean hasValue() {
        return value.get() != null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy