1 package org.apache.lucene.util;
3 import java.util.concurrent.atomic.AtomicBoolean;
6 * Licensed to the Apache Software Foundation (ASF) under one or more
7 * contributor license agreements. See the NOTICE file distributed with
8 * this work for additional information regarding copyright ownership.
9 * The ASF licenses this file to You under the Apache License, Version 2.0
10 * (the "License"); you may not use this file except in compliance with
11 * the License. You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
23 * A convenient class which offers a semi-immutable object wrapper
24 * implementation which allows one to set the value of an object exactly once,
25 * and retrieve it many times. If {@link #set(Object)} is called more than once,
26 * {@link AlreadySetException} is thrown and the operation
29 * @lucene.experimental
31 public final class SetOnce<T> {
33 /** Thrown when {@link SetOnce#set(Object)} is called more than once. */
34 public static final class AlreadySetException extends RuntimeException {
35 public AlreadySetException() {
36 super("The object cannot be set twice!");
40 private volatile T obj = null;
41 private final AtomicBoolean set;
44 * A default constructor which does not set the internal object, and allows
45 * setting it by calling {@link #set(Object)}.
48 set = new AtomicBoolean(false);
52 * Creates a new instance with the internal object set to the given object.
53 * Note that any calls to {@link #set(Object)} afterwards will result in
54 * {@link AlreadySetException}
56 * @throws AlreadySetException if called more than once
59 public SetOnce(T obj) {
61 set = new AtomicBoolean(true);
64 /** Sets the given object. If the object has already been set, an exception is thrown. */
65 public final void set(T obj) {
66 if (set.compareAndSet(false, true)) {
69 throw new AlreadySetException();
73 /** Returns the object set by {@link #set(Object)}. */
74 public final T get() {