pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / src / java / org / apache / lucene / util / SetOnce.java
1 package org.apache.lucene.util;
2
3 import java.util.concurrent.atomic.AtomicBoolean;
4
5 /**
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
12  *
13  *     http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  */
21
22 /**
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
27  * will fail.
28  *
29  * @lucene.experimental
30  */
31 public final class SetOnce<T> {
32
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!");
37     }
38   }
39   
40   private volatile T obj = null;
41   private final AtomicBoolean set;
42   
43   /**
44    * A default constructor which does not set the internal object, and allows
45    * setting it by calling {@link #set(Object)}.
46    */
47   public SetOnce() {
48     set = new AtomicBoolean(false);
49   }
50
51   /**
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}
55    *
56    * @throws AlreadySetException if called more than once
57    * @see #set(Object)
58    */
59   public SetOnce(T obj) {
60     this.obj = obj;
61     set = new AtomicBoolean(true);
62   }
63   
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)) {
67       this.obj = obj;
68     } else {
69       throw new AlreadySetException();
70     }
71   }
72   
73   /** Returns the object set by {@link #set(Object)}. */
74   public final T get() {
75     return obj;
76   }
77 }