1 /*
  2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package jdk.internal.vm.annotation;
 27 
 28 import java.lang.annotation.*;
 29 
 30 /**
 31  * A field may be annotated as "stable" to indicate that it is a
 32  * <em>stable variable</em>, expected to change its value just once.
 33  * All Java fields are initialized by the VM with a default value
 34  * (null or zero).  A properly used stable field will be set
 35  * just once to a non-default value, and keep that value forever.
 36  * While the field contains its default (null or zero) value,
 37  * the VM treats it as an ordinary mutable variable.  When a
 38  * non-default value is stored into the field, the VM is permitted
 39  * to assume that no more significant changes will occur.  This in
 40  * turn enables the VM to optimize uses of the stable variable, treating
 41  * them as constant values.  This behavior is a useful building block
 42  * for lazy evaluation or memoization of results.  In rare and subtle
 43  * use cases, stable variables may also assume multiple values over
 44  * time, with effects as described below.
 45  * <p>
 46  * <em>(Warning: the {@code @Stable} annotation is intended for use in the
 47  * JDK implemention, and with the HotSpot VM, to support optimization
 48  * of classes and algorithms defined by the JDK.  It is unavailable
 49  * outside the JDK.)</em>
 50  *
 51  * <h2><a id="lifecycle"></a>Stable Variable Life Cycle</h2>
 52  *
 53  * For example, suppose a class has two non-final fields of type
 54  * {@code int} and {@code String}.  Annotating the field declarations
 55  * with {@code @Stable} creates a pair of stable variables.  The
 56  * fields are initialized to zero and the null reference,
 57  * respectively, in the usual way, but storing a non-zero integer in
 58  * the first field or a non-null reference in the second field will
 59  * enable the VM to expect that the stored value is now the permanent
 60  * value of the field, going forward.  This condition may be used by
 61  * the VM compiler to improve code quality more aggressively,
 62  * if the VM compiler runs after the stable variable has been
 63  * given a permanent value, and chooses to observe that value.
 64  * <p>
 65  * Since all heap variables begin with a default null value for
 66  * references (resp., zero for primitives), there is an ambiguity when
 67  * the VM discovers a stable variable holding a null or primitive zero
 68  * value.  Does the user intend the VM to constant fold that
 69  * (uninteresting) value?  Or is the user waiting until later to
 70  * assign a permanent value to the variable?  The VM does not
 71  * systematically record stores of a null (resp., zero) to a stable variable,
 72  * so there is no way for the VM to decide if a field's current value is
 73  * its undisturbed initial value, or has been overwritten with
 74  * an intentionally stored null (resp., zero).  This is why the
 75  * programmer should store non-default values into stable variables,
 76  * if the consequent optimization is desired.
 77  * <p>
 78  * A stable variable may be assigned its permanent value inside a class or
 79  * object initializer, but in general (with lazy data structures)
 80  * stable variables are assigned much later.  Depending on the value
 81  * stored and what races are possible, safe publication may require
 82  * special handling with a {@code VarHandle} atomic method.
 83  * (See below.)
 84  * <p>
 85  * If an application requires constant folding of a stable variable
 86  * whose permanent value may be the default value (null or zero),
 87  * the variable can be refactored to add an extra indirection.
 88  * This would represent the default value in a non-null "box",
 89  * such as {@code Integer.valueOf(0)} or a lambda like
 90  * {@code ()->null}.  Such a refactoring should always be possible,
 91  * since stable variables should (obviously) never be part of public
 92  * APIs.
 93  *
 94  * <h2><a id="arrays"></a>Stable Arrays</h2>
 95  *
 96  * So far, stable variables are fields, but they can be array
 97  * components as well.  If a stable field is declared as an array
 98  * type with one dimension, both that array as a whole, and its
 99  * eventual components, are treated as independent stable variables.
100  * When a reference to an array of length <i>N</i> is stored to the
101  * field, then the array object itself is taken to be a constant, as
102  * with any stable field.  But then all <i>N</i> of the array
103  * components are <em>also</em> treated as independent stable
104  * variables.  Such a stable array may contain any type, reference or
105  * primitive.  Such an array may be also marked {@code final}, and
106  * initialized eagerly in the class or object initializer method.
107  * Whether any (or all) of its components are also initialized eagerly
108  * is up to the application.
109  * <p>
110  * More generally, if a stable field is declared as an array type with
111  * <em>D</em> dimensions, then all the non-null components of the
112  * array, and of any sub-arrays up to a nesting depth less than
113  * <em>D</em>, are treated as stable variables.  Thus, a stable field
114  * declared as an array potentially defines a tree (of fixed depth
115  * <em>D</em>) containing many stable variables, with each such stable
116  * variable being independently considered for optimization.  In this
117  * way, and depending on program execution, a single {@code Stable}
118  * annotation can potentially create many independent stable
119  * variables.  Since the top-level array reference is always stable,
120  * it is in general a bad idea to resize the array, even while keeping
121  * all existing components unchanged.  (This could be relaxed in the
122  * future, to allow expansion of stable arrays, if there were a use
123  * case that could deal correctly with races.  But it would require
124  * careful treatment by the compiler, to avoid folding the wrong
125  * version of an array.  Anyway, there are other options, such as
126  * tree structures, for organizing the expansion of bundles of stable
127  * variables.)
128  * <p>
129  * An array is never intrinsically stable.  There is no change made to
130  * an array as it is assigned to a stable variable of array type.
131  * This is true even though after such an assignment, the compiler may
132  * observe that array and treat its components as stable variables.
133  * If the array is aliased to some other variable, uses via that
134  * variable will not be treated as stable.  (Such aliasing is not
135  * recommended!)  Also, storing an array into a stable variable will
136  * not make that array's components into stable variables, unless the
137  * variable into which it is stored is statically typed as an array,
138  * in the declaration of the stable field which refers to that array,
139  * directly or indirectly.
140  *
141  * <h2><a id="examples"></a>Examples of Stable Variables</h2>
142  *
143  * In the following example, the only constant-foldable string stored
144  * in any stable variable is the string {@code "S"}.  All subarrays are
145  * constant.
146  *
147  * <pre>{@code
148  * @Stable String FIELD = null;  // no foldable value yet
149  * @Stable int IDNUM = 0;  // no foldable value yet
150  * @Stable boolean INITIALIZED = false;  // no foldable value yet
151  * @Stable Object[] ARRAY = {
152  *   "S",   // string "S" is foldable
153  *   new String[] { "X", "Y" },  // array is foldable, not elements
154  *   null  // null is not foldable
155  * };
156  * @Stable Object[][] MATRIX = {
157  *   { "S", "S" },   // constant value
158  *   { new String[] { "X", "Y" } },  // array is foldable, not elements
159  *   { null, "S" },  // array is foldable, but not the null
160  *   null       // could be a foldable subarray later
161  * };
162  * }</pre>
163  *
164  * When the following method is called, some of the above stable
165  * variables will gain their permanent value, a constant-foldable
166  * string "S", or a non-default primitive value.
167  *
168  * <pre>{@code
169  * void publishSomeStables() {
170  *   // store some more foldable "S" values:
171  *   FIELD = "S";
172  *   ARRAY[2] = "S";
173  *   MATRIX[2][0] = "S";
174  *   MATRIX[3] = new Object[] { "S", "S", null };
175  *   // and store some foldable primitives:
176  *   IDNUM = 42;
177  *   INITIALIZED = true;
178  *   VarHandle.releaseFence();  //optional, see below
179  * }
180  * }</pre>
181  *
182  * <p>
183  * Note that a stable boolean variable (i.e., a stable
184  * field like {@code INITIALIZED}, or a stable boolean
185  * array element) can be constant-folded,
186  * but only after it is set to {@code true}.  Even this simple
187  * optimization is sometimes useful for responding to a permanent
188  * one-shot state change, in such a way that the compiler can remove
189  * dead code associated with the initial state.  As with any stable
190  * variable, it is in general a bad idea to reset such a variable to
191  * its default (i.e., {@code false}), since compiled code might have
192  * captured the {@code true} value as a constant, and as long as that
193  * compiled code is in use, the reset value will go undetected.
194  *
195  * <h2><a id="final"></a>Final Variables, Stable Variables, and Memory Effects</h2>
196  *
197  * Fields which are declared {@code final} may also be annotated as stable.
198  * Since final fields already behave as stable variables, such an annotation
199  * conveys no additional information regarding change of the field's value, but
200  * it conveys information regarding changes to additional component variables if
201  * the type of the field is an array type (as described above).
202  * <p>
203  * In order to assist refactoring between {@code final} and
204  * {@code @Stable} field declarations, the Java Memory Model
205  * <em>freeze</em> operation is applied to both kinds of fields, when
206  * the assignment occurs in a class or object initializer (i.e.,
207  * static initialization code in {@code <clinit>} or constructor code
208  * in {@code <init>}).  The freezing of a final or stable field is
209  * (currently) triggered only when an actual assignment occurs, directly
210  * from the initializer method ({@code <clinit>} or {@code <init>}).
211  * It is implemented in HotSpot by an appropriate memory barrier
212  * instruction at the return point of the initializer method.  In this
213  * way, any non-null (or non-zero) value stored to a stable variable
214  * (either field or array component) will appear without races to any
215  * user of the class or object that has been initialized.
216  * <p>
217  * (Note: The barrier action of a class initializer is implicit in the
218  * unlocking operation specified in JVMS 5.5, Step 10.  The barrier
219  * action of an instance initializer is specified as a "freeze action"
220  * in JLS 17.5.1.  These disparate barrier actions have parallel
221  * effects on static and non-static final and stable variables.)
222  * <p>
223  * There is no such JMM freeze operation applied to stable field stores in
224  * any other context.  This implies that a constructor may choose to
225  * initialize a stable variable, rather than "leaving it for later".
226  * Such an initial value will be safely published, as if the field were
227  * {@code final}.  The stored value may (or may not) contain
228  * additional stable variables, not yet initialized.  Note that if a
229  * stable variable is written outside of the code of a constructor (or
230  * class initializer), then data races are possible, just the same as
231  * if there were no {@code @Stable} annotation, and the field were a
232  * regular mutable field.  In fact, the usual case for lazily
233  * evaluated data structures is to assign to stable variables much
234  * later than the enclosing data structure is created.  This means
235  * that racing reads and writes might observe nulls (or primitive
236  * zeroes) as well as non-default values.
237  *
238  * <h2><a id="usage"></a>Proper Handling of Stable Variables</h2>
239  *
240  * A stable variable can appear to be in either of two states,
241  * either uninitialized, or else set to a permanent, foldable value.
242  * Therefore, most code which reads stable variables should not assume
243  * that the value has been set, and should dynamically test for a null
244  * (or zero) value.  Code which cannot prove a previous initialization
245  * must perform a null (or zero) test on a value loaded
246  * from a stable variable.  Code which omits the null (or zero) test should be
247  * documented as to why the initialization order is reliable.  In
248  * general, some sort of critical section for initialization should be
249  * documented, as provably preceding all uses of the (unchecked)
250  * stable variable, or else reasons should be given why races are
251  * benign, or some other proof given that races are either excluded or
252  * benign.  See below for further discussion.
253  * <p>
254  * After constant folding, the compiler can make use of many aspects of
255  * the object: its dynamic type, its length (if it is an array), and
256  * the values of its fields (if they are themselves constants, either
257  * final or stable).  It is in general a bad idea to reset such
258  * variables to any other value, since compiled code might have folded
259  * an earlier stored value, and will never detect the reset value.
260  * <p>
261  * The HotSpot interpreter is not fully aware of stable annotations,
262  * and treats annotated fields (and any affected arrays) as regular
263  * mutable variables.  Thus, a field annotated as {@code @Stable} may
264  * be given a series of values, by explicit assignment, by reflection,
265  * or by some other means.  If the HotSpot compiler constant-folds a
266  * stable variable, then in some contexts (execution of fully
267  * optimized code) the variable will appear to have one "historical"
268  * value, observed, captured, and used within the compiled code to the
269  * exclusion of any other possible values.  Meanwhile, in other less
270  * optimized contexts, the stable variable will appear to have a more
271  * recent value.  Race conditions, if allowed, will make this even
272  * more complex, since with races there is no definable "most recent"
273  * value across all threads.  The compiler can observe any racing
274  * value, as it runs concurrently to the application, in its own
275  * thread.
276  * <p>
277  * It is no good to try to "reset" a stable variable by storing its
278  * default again, because there is (currently) no way to find and
279  * deoptimize any and all affected compiled code.  If you need the
280  * bookkeeping, try {@code SwitchPoint} or {@code MutableCallSite},
281  * which both are able to reset compiled code that has captured an
282  * intermediate state.
283  * <p>
284  * Note also each compilation task makes its own decisions about
285  * whether to observe stable variable values, and how aggressively to
286  * constant-fold them.  And a method that uses a stable variable might
287  * be inlined by many different compilation tasks.  The net result of
288  * all this is that, if stable variables are multiply assigned, the
289  * program execution may observe any "historical" value (if it was
290  * captured by some particular compilation task), as well as a "most
291  * recent" value observed by the interpreter or less-optimized code.
292  * <p>
293  * For all these reasons, a user who bends the rules for a stable
294  * variable, by assigning several values to it, must state the
295  * intended purposes carefully in warning documentation on the
296  * relevant stable field declaration.  That user's code must function
297  * correctly when observing any or all of the assigned values, at any
298  * time.  Alternatively, field assignments must be constrained
299  * appropriately so that unwanted values are not observable by
300  * compiled code.
301  * <p>
302  * Any class which uses this annotation is responsible for
303  * constraining assignments in such a way as not to violate API
304  * contracts of the class.  (If the chosen technique is unusual in
305  * some way, it should be documented in a comment on the field.)  Such
306  * constraints can be arranged in a variety of ways:
307  * <ul><li> using the {@code VarHandle} API to perform an explicit
308  * atomic operation such as {@code compareAndExchange},
309  * {@code setRelease}, {@code releaseFence}, or the like.
310  * </li><li> using regular variable access under explicit sychronization
311  * </li><li> using some other kind of critical section to avoid races
312  * which could affect compiled code
313  * </li><li> allowing multiple assignments under benign races, but
314  * only of some separately uniquified value
315  * </li><li> allowing multiple assignments under benign races, but
316  * only of semantically equivalent values, perhaps permitting
317  * occasional duplication of cached values
318  * </li><li> concealing the effects of multiple assignments in some
319  * other API-dependent way
320  * </li><li> providing some other internal proof of correctness, while
321  * accounting for all possible racing API accesses
322  * </li><li> making some appropriate disclaimer in the API about
323  * undefined behavior
324  * </li></ul>
325  * <p>
326  * There may be special times when constant folding of stable
327  * variables is disabled.  Such times would amount to a critical
328  * section locking out the compiler from reading stable variables.
329  * During such a critical section, an uninitialized stable variable
330  * can be changed in any way, just like a regular mutable variable
331  * (field or array component).  It can even be reset to its default.
332  * Specifically, this may happen during certain AOT operations.  If a
333  * stable variable can be updated multiple times during such a
334  * critical section, that fact must be clearly stated as a comment on
335  * the field declaration.  (In the future, there may be explicit
336  * AOT-related annotations to convey this use case.)  If there is no
337  * such warning, maintainers can safely disregard the possibility of
338  * an AOT critical section, since the author of the stable variable is
339  * relying on one of the other techniques listed above.
340  * <p>
341  * It is possible to imagine markings for foldable methods or fields,
342  * which can constant-fold a wider variety of states and values.  This
343  * annotation does not readily extend to such things, for the simple
344  * reason that extra VM bookkeeping would be required to record a
345  * wider variety of candidate states for constant folding.  Such
346  * higher-level mechanisms may be created in the future.  The present
347  * low-level annotation is designed as a potential building block to
348  * manage their bookkeeping.
349  *
350  * @implNote
351  * This annotation only takes effect for fields of classes loaded by the boot
352  * loader.  Annotations on fields of classes loaded outside of the boot loader
353  * are ignored.
354  */
355 @Target(ElementType.FIELD)
356 @Retention(RetentionPolicy.RUNTIME)
357 public @interface Stable {
358 }