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

com.spotify.zoltar.loaders.Preloader Maven / Gradle / Ivy

There is a newer version: 0.6.0
Show newest version
/*-
 * -\-\-
 * zoltar-core
 * --
 * Copyright (C) 2016 - 2018 Spotify AB
 * --
 * 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.spotify.zoltar.loaders;

import com.spotify.zoltar.Model;
import com.spotify.zoltar.ModelLoader;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;

/**
 * Preloader is model loader that calls {@link ModelLoader#get()} allowing model preloading.
 *
 * @param  Model instance type.
 */
@FunctionalInterface
public interface Preloader> extends ModelLoader {

  /**
   * Returns a blocking {@link Preloader}. Blocks at create time till the model is loaded.
   */
  static > Function, Preloader> preload() {
    return preload(Duration.ofDays(Integer.MAX_VALUE));
  }

  /**
   * Returns a blocking {@link Preloader}. Blocks till the model is loaded or a {@link Duration} is
   * met.
   *
   * @param duration Amount of time that it should wait, if necessary, for model to be loaded.
   */
  static > Function, Preloader> preload(
      final Duration duration) {
    return loader -> {
      CompletionStage model;
      try {
        model = CompletableFuture.completedFuture(loader.get(duration));
      } catch (final Exception e) {
        final CompletableFuture failed = new CompletableFuture<>();
        failed.completeExceptionally(e);

        model = failed;
      }

      final CompletionStage finalModel = model;
      return () -> finalModel;
    };
  }

  /**
   * Returns a asynchronous {@link Preloader}.
   */
  static > Function, Preloader> preloadAsync() {
    return loader -> {
      final CompletionStage model = loader.get();
      return () -> model;
    };
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy