1 /*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15
16 package software.amazon.awssdk.core.internal.http.loader;
17
18 import static software.amazon.awssdk.utils.Validate.notNull;
19
20 import java.util.Optional;
21 import software.amazon.awssdk.annotations.SdkInternalApi;
22
23 /**
24 * Decorator of {@link SdkHttpServiceProvider} to provide lazy initialized caching.
25 */
26 @SdkInternalApi
27 final class CachingSdkHttpServiceProvider<T> implements SdkHttpServiceProvider<T> {
28
29 private final SdkHttpServiceProvider<T> delegate;
30
31 /**
32 * We assume that the service obtained from the provider chain will always be the same (even if it's an empty optional) so
33 * we cache it as a field.
34 */
35 private volatile Optional<T> factory;
36
37 CachingSdkHttpServiceProvider(SdkHttpServiceProvider<T> delegate) {
38 this.delegate = notNull(delegate, "Delegate service provider cannot be null");
39 }
40
41 @Override
42 public Optional<T> loadService() {
43 if (factory == null) {
44 synchronized (this) {
45 if (factory == null) {
46 this.factory = delegate.loadService();
47 }
48 }
49 }
50 return factory;
51 }
52 }
53