• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GENERATED SOURCE. DO NOT MODIFY. */
2 // © 2016 and later: Unicode, Inc. and others.
3 // License & terms of use: http://www.unicode.org/copyright.html
4 /*
5  ******************************************************************************
6  * Copyright (C) 2005-2016, International Business Machines Corporation and    *
7  * others. All Rights Reserved.                                               *
8  ******************************************************************************
9 */
10 package android.icu.util;
11 
12 /**
13  * Provides a flexible mechanism for controlling access, without requiring that
14  * a class be immutable. Once frozen, an object can never be unfrozen, so it is
15  * thread-safe from that point onward. Once the object has been frozen,
16  * it must guarantee that no changes can be made to it. Any attempt to alter
17  * it must raise an UnsupportedOperationException exception. This means that when
18  * the object returns internal objects, or if anyone has references to those internal
19  * objects, that those internal objects must either be immutable, or must also
20  * raise exceptions if any attempt to modify them is made. Of course, the object
21  * can return clones of internal objects, since those are safe.
22  * <h2>Background</h2>
23  * <p>
24  * There are often times when you need objects to be objects 'safe', so that
25  * they can't be modified. Examples are when objects need to be thread-safe, or
26  * in writing robust code, or in caches. If you are only creating your own
27  * objects, you can guarantee this, of course -- but only if you don't make a
28  * mistake. If you have objects handed into you, or are creating objects using
29  * others handed into you, it is a different story. It all comes down to whether
30  * you want to take the Blanche Dubois approach (&quot;depend on the kindness of
31  * strangers&quot;) or the Andy Grove approach (&quot;Only the Paranoid
32  * Survive&quot;).
33  * </p>
34  * <p>
35  * For example, suppose we have a simple class:
36  * </p>
37  *
38  * <pre>
39  * public class A {
40  *      protected Collection b;
41  *
42  *      protected Collection c;
43  *
44  *      public Collection get_b() {
45  *              return b;
46  *      }
47  *
48  *      public Collection get_c() {
49  *              return c;
50  *      }
51  *
52  *      public A(Collection new_b, Collection new_c) {
53  *              b = new_b;
54  *              c = new_c;
55  *      }
56  * }
57  * </pre>
58  *
59  * <p>
60  * Since the class doesn't have any setters, someone might think that it is
61  * immutable. You know where this is leading, of course; this class is unsafe in
62  * a number of ways. The following illustrates that.
63  * </p>
64  *
65  * <pre>
66  *  public test1(SupposedlyImmutableClass x, SafeStorage y) {
67  *    // unsafe getter
68  *    A a = x.getA();
69  *    Collection col = a.get_b();
70  *    col.add(something); // a has now been changed, and x too
71  *
72  *    // unsafe constructor
73  *    a = new A(col, col);
74  *    y.store(a);
75  *    col.add(something); // a has now been changed, and y too
76  *  }
77  * </pre>
78  *
79  * <p>
80  * There are a few different techniques for having safe classes.
81  * </p>
82  * <ol>
83  * <li>Const objects. In C++, you can declare parameters const.</li>
84  * <li>Immutable wrappers. For example, you can put a collection in an
85  * immutable wrapper.</li>
86  * <li>Always-Immutable objects. Java uses this approach, with a few
87  * variations. Examples:
88  * <ol>
89  * <li>Simple. Once a Color is created (eg from R, G, and B integers) it is
90  * immutable.</li>
91  * <li>Builder Class. There is a separate 'builder' class. For example,
92  * modifiable Strings are created using StringBuffer (which doesn't have the
93  * full String API available). Once you want an immutable form, you create one
94  * with toString().</li>
95  * <li>Primitives. These are always safe, since they are copied on input/output
96  * from methods.</li>
97  * </ol>
98  * </li>
99  * <li>Cloning. Where you need an object to be safe, you clone it.</li>
100  * </ol>
101  * <p>
102  * There are advantages and disadvantages of each of these.
103  * </p>
104  * <ol>
105  * <li>Const provides a certain level of protection, but since const can be and
106  * is often cast away, it only protects against most inadvertent mistakes. It
107  * also offers no threading protection, since anyone who has a pointer to the
108  * (unconst) object in another thread can mess you up.</li>
109  * <li>Immutable wrappers are safer than const in that the constness can't be
110  * cast away. But other than that they have all the same problems: not safe if
111  * someone else keeps hold of the original object, or if any of the objects
112  * returned by the class are mutable.</li>
113  * <li>Always-Immutable Objects are safe, but usage can require excessive
114  * object creation.</li>
115  * <li>Cloning is only safe if the object truly has a 'safe' clone; defined as
116  * one that <i>ensures that no change to the clone affects the original</i>.
117  * Unfortunately, many objects don't have a 'safe' clone, and always cloning can
118  * require excessive object creation.</li>
119  * </ol>
120  * <h2>Freezable Model</h2>
121  * <p>
122  * The <code>Freezable</code> model supplements these choices by giving you
123  * the ability to build up an object by calling various methods, then when it is
124  * in a final state, you can <i>make</i> it immutable. Once immutable, an
125  * object cannot <i>ever </i>be modified, and is completely thread-safe: that
126  * is, multiple threads can have references to it without any synchronization.
127  * If someone needs a mutable version of an object, they can use
128  * <code>cloneAsThawed()</code>, and modify the copy. This provides a simple,
129  * effective mechanism for safe classes in circumstances where the alternatives
130  * are insufficient or clumsy. (If an object is shared before it is immutable,
131  * then it is the responsibility of each thread to mutex its usage (as with
132  * other objects).)
133  * </p>
134  * <p>
135  * Here is what needs to be done to implement this interface, depending on the
136  * type of the object.
137  * </p>
138  * <h3><b>Immutable Objects</b></h3>
139  * <p>
140  * These are the easiest. You just use the interface to reflect that, by adding
141  * the following:
142  * </p>
143  *
144  * <pre>
145  *  public class A implements Freezable&lt;A&gt; {
146  *   ...
147  *   public final boolean isFrozen() {return true;}
148  *   public final A freeze() {return this;}
149  *   public final A cloneAsThawed() { return this; }
150  *   }
151  * </pre>
152  *
153  * <p>
154  * These can be final methods because subclasses of immutable objects must
155  * themselves be immutable. (Note: <code>freeze</code> is returning
156  * <code>this</code> for chaining.)
157  * </p>
158  * <h3><b>Mutable Objects</b></h3>
159  * <p>
160  * Add a protected 'flagging' field:
161  * </p>
162  *
163  * <pre>
164  * protected volatile boolean frozen; // WARNING: must be volatile
165  * </pre>
166  *
167  * <p>
168  * Add the following methods:
169  * </p>
170  *
171  * <pre>
172  * public final boolean isFrozen() {
173  *      return frozen;
174  * };
175  *
176  * public A freeze() {
177  *      frozen = true;  // WARNING: must be final statement before return
178  *      return this;
179  * }
180  * </pre>
181  *
182  * <p>
183  * Add a <code>cloneAsThawed()</code> method following the normal pattern for
184  * <code>clone()</code>, except that <code>frozen=false</code> in the new
185  * clone.
186  * </p>
187  * <p>
188  * Then take the setters (that is, any method that can change the internal state
189  * of the object), and add the following as the first statement:
190  * </p>
191  *
192  * <pre>
193  * if (isFrozen()) {
194  *      throw new UnsupportedOperationException(&quot;Attempt to modify frozen object&quot;);
195  * }
196  * </pre>
197  *
198  * <h4><b>Subclassing</b></h4>
199  * <p>
200  * Any subclass of a <code>Freezable</code> will just use its superclass's
201  * flagging field. It must override <code>freeze()</code> and
202  * <code>cloneAsThawed()</code> to call the superclass, but normally does not
203  * override <code>isFrozen()</code>. It must then just pay attention to its
204  * own getters, setters and fields.
205  * </p>
206  * <h4><b>Internal Caches</b></h4>
207  * <p>
208  * Internal caches are cases where the object is logically unmodified, but
209  * internal state of the object changes. For example, there are const C++
210  * functions that cast away the const on the &quot;this&quot; pointer in order
211  * to modify an object cache. These cases are handled by mutexing the internal
212  * cache to ensure thread-safety. For example, suppose that UnicodeSet had an
213  * internal marker to the last code point accessed. In this case, the field is
214  * not externally visible, so the only thing you need to do is to synchronize
215  * the field for thread safety.
216  * </p>
217  * <h4>Unsafe Internal Access</h4>
218  * <p>
219  * Internal fields are called <i>safe</i> if they are either
220  * <code>frozen</code> or immutable (such as String or primitives). If you've
221  * never allowed internal access to these, then you are all done. For example,
222  * converting UnicodeSet to be <code>Freezable</code> is just accomplished
223  * with the above steps. But remember that you <i><b>have</b></i> allowed
224  * access to unsafe internals if you have any code like the following, in a
225  * getter, setter, or constructor:
226  * </p>
227  *
228  * <pre>
229  * Collection getStuff() {
230  *      return stuff;
231  * } // caller could keep reference &amp; modify
232  *
233  * void setStuff(Collection x) {
234  *      stuff = x;
235  * } // caller could keep reference &amp; modify
236  *
237  * MyClass(Collection x) {
238  *      stuff = x;
239  * } // caller could keep reference &amp; modify
240  * </pre>
241  *
242  * <p>
243  * These also illustrated in the code sample in <b>Background</b> above.
244  * </p>
245  * <p>
246  * To deal with unsafe internals, the simplest course of action is to do the
247  * work in the <code>freeze()</code> function. Just make all of your internal
248  * fields frozen, and set the frozen flag. Any subsequent getter/setter will
249  * work properly. Here is an example:
250  * </p>
251  * <p><b>Warning!</b> The 'frozen' boolean MUST be volatile, and must be set as the last statement
252  * in the method.</p>
253  * <pre>
254  * public A freeze() {
255  *      if (!frozen) {
256  *              foo.freeze();
257  *              frozen = true;
258  *      }
259  *      return this;
260  * }
261  * </pre>
262  *
263  * <p>
264  * If the field is a <code>Collection</code> or <code>Map</code>, then to
265  * make it frozen you have two choices. If you have never allowed access to the
266  * collection from outside your object, then just wrap it to prevent future
267  * modification.
268  * </p>
269  *
270  * <pre>
271  * zone_to_country = Collections.unmodifiableMap(zone_to_country);
272  * </pre>
273  *
274  * <p>
275  * If you have <i>ever</i> allowed access, then do a <code>clone()</code>
276  * before wrapping it.
277  * </p>
278  *
279  * <pre>
280  * zone_to_country = Collections.unmodifiableMap(zone_to_country.clone());
281  * </pre>
282  *
283  * <p>
284  * If a collection <i>(or any other container of objects)</i> itself can
285  * contain mutable objects, then for a safe clone you need to recurse through it
286  * to make the entire collection immutable. The recursing code should pick the
287  * most specific collection available, to avoid the necessity of later
288  * downcasing.
289  * </p>
290  * <blockquote>
291  * <p>
292  * <b>Note: </b>An annoying flaw in Java is that the generic collections, like
293  * <code>Map</code> or <code>Set</code>, don't have a <code>clone()</code>
294  * operation. When you don't know the type of the collection, the simplest
295  * course is to just create a new collection:
296  * </p>
297  *
298  * <pre>
299  * zone_to_country = Collections.unmodifiableMap(new HashMap(zone_to_country));
300  * </pre>
301  *
302  * </blockquote>
303  */
304 public interface Freezable<T> extends Cloneable {
305     /**
306      * Determines whether the object has been frozen or not.
307      */
isFrozen()308     public boolean isFrozen();
309 
310     /**
311      * Freezes the object.
312      * @return the object itself.
313      */
freeze()314     public T freeze();
315 
316     /**
317      * Provides for the clone operation. Any clone is initially unfrozen.
318      */
cloneAsThawed()319     public T cloneAsThawed();
320 }
321