/driver-core/src/main/com/mongodb/internal/inject/SameObjectProvider.java

https://github.com/jyemin/mongo-java-driver · Java · 59 lines · 34 code · 10 blank · 15 comment · 2 complexity · 055df99b31b5da2181fa952707dd0338 MD5 · raw file

  1. /*
  2. * Copyright 2008-present MongoDB, Inc.
  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. * http://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 com.mongodb.internal.inject;
  17. import com.mongodb.annotations.ThreadSafe;
  18. import com.mongodb.lang.Nullable;
  19. import java.util.Optional;
  20. import java.util.concurrent.atomic.AtomicReference;
  21. import static com.mongodb.assertions.Assertions.assertNotNull;
  22. import static com.mongodb.assertions.Assertions.assertTrue;
  23. @ThreadSafe
  24. public final class SameObjectProvider<T> implements Provider<T> {
  25. private final AtomicReference<T> object;
  26. private SameObjectProvider(final @Nullable T o) {
  27. object = new AtomicReference<>();
  28. if (o != null) {
  29. initialize(o);
  30. }
  31. }
  32. @Override
  33. public T get() {
  34. return assertNotNull(object.get());
  35. }
  36. @Override
  37. public Optional<T> optional() {
  38. return Optional.of(get());
  39. }
  40. public void initialize(final T o) {
  41. assertTrue(object.compareAndSet(null, o));
  42. }
  43. public static <T> SameObjectProvider<T> initialized(final T o) {
  44. return new SameObjectProvider<>(o);
  45. }
  46. public static <T> SameObjectProvider<T> uninitialized() {
  47. return new SameObjectProvider<>(null);
  48. }
  49. }