|
| 1 | +/* |
| 2 | + * Copyright 2017-2020 original authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.micronaut.context; |
| 17 | + |
| 18 | + |
| 19 | +import javax.inject.Provider; |
| 20 | +import javax.validation.constraints.NotNull; |
| 21 | + |
| 22 | +/** |
| 23 | + * Helper methods for dealing with {@link javax.inject.Provider}. |
| 24 | + * |
| 25 | + * @author Denis Stepanov |
| 26 | + * @since 2.0.2 |
| 27 | + */ |
| 28 | +public class ProviderUtils { |
| 29 | + |
| 30 | + /** |
| 31 | + * Caches the result of provider in a thread safe manner. |
| 32 | + * |
| 33 | + * @param delegate The provider providing the result |
| 34 | + * @param <T> The type of result |
| 35 | + * @return A new provider that will cache the result |
| 36 | + */ |
| 37 | + public static <T> Provider<T> memoized(Provider<T> delegate) { |
| 38 | + return new MemoizingProvider<>(delegate); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * A lazy provider. |
| 43 | + * |
| 44 | + * @param <T> The type |
| 45 | + * @author Denis Stepanov |
| 46 | + * @since 2.0.2 |
| 47 | + */ |
| 48 | + private static final class MemoizingProvider<T> implements Provider<T> { |
| 49 | + |
| 50 | + private Provider<T> actual; |
| 51 | + private Provider<T> delegate = this::initialize; |
| 52 | + private boolean initialized; |
| 53 | + |
| 54 | + MemoizingProvider(@NotNull Provider<T> actual) { |
| 55 | + this.actual = actual; |
| 56 | + } |
| 57 | + |
| 58 | + @Override |
| 59 | + public T get() { |
| 60 | + return delegate.get(); |
| 61 | + } |
| 62 | + |
| 63 | + private synchronized T initialize() { |
| 64 | + if (!initialized) { |
| 65 | + T value = actual.get(); |
| 66 | + delegate = () -> value; |
| 67 | + initialized = true; |
| 68 | + actual = null; |
| 69 | + } |
| 70 | + return delegate.get(); |
| 71 | + } |
| 72 | + |
| 73 | + @Override |
| 74 | + public String toString() { |
| 75 | + if (initialized) { |
| 76 | + return "Provider of " + delegate.get(); |
| 77 | + } |
| 78 | + return "ProviderUtils.memoized(" + actual + ")"; |
| 79 | + } |
| 80 | + |
| 81 | + } |
| 82 | +} |
0 commit comments