1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package jsr166e; |
8 |
|
9 |
/** |
10 |
* <b>This file exists for documentation reference but is not part of |
11 |
* any planned release.</b> |
12 |
* |
13 |
* <p>A set of methods providing fine-grained control over happens-before |
14 |
* and synchronization order relations among reads and/or writes. The |
15 |
* methods of this class are designed for use in uncommon situations |
16 |
* where declaring variables {@code volatile} or {@code final}, using |
17 |
* instances of atomic classes, using {@code synchronized} blocks or |
18 |
* methods, or using other synchronization facilities are not possible |
19 |
* or do not provide the desired control. |
20 |
* |
21 |
* <p><b>Memory Ordering.</b> There are three methods for controlling |
22 |
* ordering relations among memory accesses (i.e., reads and |
23 |
* writes). Method {@code orderWrites} is typically used to enforce |
24 |
* order between two writes, and {@code orderAccesses} between a write |
25 |
* and a read. Method {@code orderReads} is used to enforce order |
26 |
* between two reads with respect to other {@code orderWrites} and/or |
27 |
* {@code orderAccesses} invocations. The formally specified |
28 |
* properties of these methods described below provide |
29 |
* platform-independent guarantees that are honored by all levels of a |
30 |
* platform (compilers, systems, processors). The use of these |
31 |
* methods may result in the suppression of otherwise valid compiler |
32 |
* transformations and optimizations that could visibly violate the |
33 |
* specified orderings, and may or may not entail the use of |
34 |
* processor-level "memory barrier" instructions. |
35 |
* |
36 |
* <p>Each ordering method accepts a {@code ref} argument, and |
37 |
* controls ordering among accesses with respect to this reference. |
38 |
* Invocations must be placed <em>between</em> accesses performed in |
39 |
* expression evaluations and assignment statements to control the |
40 |
* orderings of prior versus subsequent accesses appearing in program |
41 |
* order. These methods also return their arguments to simplify |
42 |
* correct usage in these contexts. |
43 |
* |
44 |
* <p>Usages of ordering methods almost always take one of the forms |
45 |
* illustrated in the examples below. These idioms arrange some of |
46 |
* the ordering properties associated with {@code volatile} and |
47 |
* related language-based constructions, but without other |
48 |
* compile-time and runtime benefits that make language-based |
49 |
* constructions far better choices when they are applicable. Usages |
50 |
* should be restricted to the control of strictly internal |
51 |
* implementation matters inside a class or package, and must either |
52 |
* avoid or document any consequent violations of ordering or safety |
53 |
* properties expected by users of a class employing them. |
54 |
* |
55 |
* <p><b>Reachability.</b> Method {@code reachabilityFence} |
56 |
* establishes an ordering for strong reachability (as defined in the |
57 |
* {@link java.lang.ref} package specification) with respect to |
58 |
* garbage collection. Method {@code reachabilityFence} differs from |
59 |
* the others in that it controls relations that are otherwise only |
60 |
* implicit in a program -- the reachability conditions triggering |
61 |
* garbage collection. As illustrated in the sample usages below, |
62 |
* this method is applicable only when reclamation may have visible |
63 |
* effects, which is possible for objects with finalizers (see Section |
64 |
* 12.6 of the Java Language Specification) that are implemented in |
65 |
* ways that rely on ordering control for correctness. |
66 |
* |
67 |
* <p><b>Sample Usages</b> |
68 |
* |
69 |
* <p><b>Safe publication.</b> With care, method {@code orderWrites} |
70 |
* may be used to obtain the memory safety effects of {@code final} |
71 |
* for a field that cannot be declared as {@code final}, because its |
72 |
* primary initialization cannot be performed in a constructor, in |
73 |
* turn because it is used in a framework requiring that all classes |
74 |
* have a no-argument constructor; as in: |
75 |
* |
76 |
* <pre> {@code |
77 |
* class WidgetHolder { |
78 |
* private Widget widget; |
79 |
* public WidgetHolder() {} |
80 |
* public static WidgetHolder newWidgetHolder(Params params) { |
81 |
* WidgetHolder h = new WidgetHolder(); |
82 |
* h.widget = new Widget(params); |
83 |
* return Fences.orderWrites(h); |
84 |
* } |
85 |
* }}</pre> |
86 |
* |
87 |
* Here, the invocation of {@code orderWrites} ensures that the |
88 |
* effects of the widget assignment are ordered before those of any |
89 |
* (unknown) subsequent stores of {@code h} in other variables that |
90 |
* make {@code h} available for use by other objects. Initialization |
91 |
* sequences using {@code orderWrites} require more care than those |
92 |
* involving {@code final} fields. When {@code final} is not used, |
93 |
* compilers cannot help you to ensure that the field is set correctly |
94 |
* across all usages. You must fully initialize objects |
95 |
* <em>before</em> the {@code orderWrites} invocation that makes |
96 |
* references to them safe to assign to accessible variables. Further, |
97 |
* initialization sequences must not internally "leak" the reference |
98 |
* by using it as an argument to a callback method or adding it to a |
99 |
* static data structure. If less constrained usages were required, |
100 |
* it may be possible to cope using more extensive sets of fences, or |
101 |
* as a normally better choice, using synchronization (locking). |
102 |
* Conversely, if it were possible to do so, the best option would be |
103 |
* to rewrite class {@code WidgetHolder} to use {@code final}. |
104 |
* |
105 |
* <p>An alternative approach is to place similar mechanics in the |
106 |
* (sole) method that makes such objects available for use by others. |
107 |
* Here is a stripped-down example illustrating the essentials. In |
108 |
* practice, among other changes, you would use access methods instead |
109 |
* of a public field. |
110 |
* |
111 |
* <pre> {@code |
112 |
* class AnotherWidgetHolder { |
113 |
* public Widget widget; |
114 |
* void publish(Widget w) { |
115 |
* this.widget = Fences.orderWrites(w); |
116 |
* } |
117 |
* // ... |
118 |
* }}</pre> |
119 |
* |
120 |
* In this case, the {@code orderWrites} invocation occurs before the |
121 |
* store making the object available. Correctness again relies on |
122 |
* ensuring that there are no leaks prior to invoking this method, and |
123 |
* that it really is the <em>only</em> means of accessing the |
124 |
* published object. This approach is not often applicable -- |
125 |
* normally you would publish objects using a thread-safe collection |
126 |
* that itself guarantees the expected ordering relations. However, it |
127 |
* may come into play in the construction of such classes themselves. |
128 |
* |
129 |
* <p><b>Safely updating fields.</b> Outside of the initialization |
130 |
* idioms illustrated above, Fence methods ordering writes must be |
131 |
* paired with those ordering reads. To illustrate, suppose class |
132 |
* {@code c} contains an accessible variable {@code data} that should |
133 |
* have been declared as {@code volatile} but wasn't: |
134 |
* |
135 |
* <pre> {@code |
136 |
* class C { |
137 |
* Object data; // need volatile access but not volatile |
138 |
* // ... |
139 |
* } |
140 |
* |
141 |
* class App { |
142 |
* Object getData(C c) { |
143 |
* return Fences.orderReads(c).data; |
144 |
* } |
145 |
* |
146 |
* void setData(C c) { |
147 |
* Object newValue = ...; |
148 |
* c.data = Fences.orderWrites(newValue); |
149 |
* Fences.orderAccesses(c); |
150 |
* } |
151 |
* // ... |
152 |
* }}</pre> |
153 |
* |
154 |
* Method {@code getData} provides an emulation of {@code volatile} |
155 |
* reads of (non-long/double) fields by ensuring that the read of |
156 |
* {@code c} obtained as an argument is ordered before subsequent |
157 |
* reads using this reference, and then performs the read of its |
158 |
* field. Method {@code setData} provides an emulation of volatile |
159 |
* writes, ensuring that all other relevant writes have completed, |
160 |
* then performing the assignment, and then ensuring that the write is |
161 |
* ordered before any other access. These techniques may apply even |
162 |
* when fields are not directly accessible, in which case calls to |
163 |
* fence methods would surround calls to methods such as {@code |
164 |
* c.getData()}. However, these techniques cannot be applied to |
165 |
* {@code long} or {@code double} fields because reads and writes of |
166 |
* fields of these types are not guaranteed to be |
167 |
* atomic. Additionally, correctness may require that all accesses of |
168 |
* such data use these kinds of wrapper methods, which you would need |
169 |
* to manually ensure. |
170 |
* |
171 |
* <p>More generally, Fence methods can be used in this way to achieve |
172 |
* the safety properties of {@code volatile}. However their use does |
173 |
* not necessarily guarantee the full sequential consistency |
174 |
* properties specified in the Java Language Specification chapter 17 |
175 |
* for programs using {@code volatile}. In particular, emulation using |
176 |
* Fence methods is not guaranteed to maintain the property that |
177 |
* {@code volatile} operations performed by different threads are |
178 |
* observed in the same order by all observer threads. |
179 |
* |
180 |
* <p><b>Acquire/Release management of threadsafe objects</b>. It may |
181 |
* be possible to use weaker conventions for volatile-like variables |
182 |
* when they are used to keep track of objects that fully manage their |
183 |
* own thread-safety and synchronization. Here, an acquiring read |
184 |
* operation remains the same as a volatile-read, but a releasing |
185 |
* write differs by virtue of not itself ensuring an ordering of its |
186 |
* write with subsequent reads, because the required effects are |
187 |
* already ensured by the referenced objects. |
188 |
* For example: |
189 |
* |
190 |
* <pre> {@code |
191 |
* class Item { |
192 |
* synchronized f(); // ALL methods are synchronized |
193 |
* // ... |
194 |
* } |
195 |
* |
196 |
* class ItemHolder { |
197 |
* private Item item; |
198 |
* Item acquireItem() { |
199 |
* return Fences.orderReads(item); |
200 |
* } |
201 |
* |
202 |
* void releaseItem(Item x) { |
203 |
* item = Fences.orderWrites(x); |
204 |
* } |
205 |
* |
206 |
* // ... |
207 |
* }}</pre> |
208 |
* |
209 |
* Because this construction avoids use of {@code orderAccesses}, |
210 |
* which is typically more costly than the other fence methods, it may |
211 |
* result in better performance than using {@code volatile} or its |
212 |
* emulation. However, as is the case with most applications of fence |
213 |
* methods, correctness relies on the usage context -- here, the |
214 |
* thread safety of {@code Item}, as well as the lack of need for full |
215 |
* volatile semantics inside this class itself. However, the second |
216 |
* concern means that it can be difficult to extend the {@code |
217 |
* ItemHolder} class in this example to be more useful. |
218 |
* |
219 |
* <p><b>Avoiding premature finalization.</b> Finalization may occur |
220 |
* whenever a Java Virtual Machine detects that no reference to an |
221 |
* object will ever be stored in the heap: A garbage collector may |
222 |
* reclaim an object even if the fields of that object are still in |
223 |
* use, so long as the object has otherwise become unreachable. This |
224 |
* may have surprising and undesirable effects in cases such as the |
225 |
* following example in which the bookkeeping associated with a class |
226 |
* is managed through array indices. Here, method {@code action} |
227 |
* uses a {@code reachabilityFence} to ensure that the Resource |
228 |
* object is not reclaimed before bookkeeping on an associated |
229 |
* ExternalResource has been performed; in particular here, to ensure |
230 |
* that the array slot holding the ExternalResource is not nulled out |
231 |
* in method {@link Object#finalize}, which may otherwise run |
232 |
* concurrently. |
233 |
* |
234 |
* <pre> {@code |
235 |
* class Resource { |
236 |
* private static ExternalResource[] externalResourceArray = ... |
237 |
* |
238 |
* int myIndex; |
239 |
* Resource(...) { |
240 |
* myIndex = ... |
241 |
* externalResourceArray[myIndex] = ...; |
242 |
* ... |
243 |
* } |
244 |
* protected void finalize() { |
245 |
* externalResourceArray[myIndex] = null; |
246 |
* ... |
247 |
* } |
248 |
* public void action() { |
249 |
* try { |
250 |
* // ... |
251 |
* int i = myIndex; |
252 |
* Resource.update(externalResourceArray[i]); |
253 |
* } finally { |
254 |
* Fences.reachabilityFence(this); |
255 |
* } |
256 |
* } |
257 |
* private static void update(ExternalResource ext) { |
258 |
* ext.status = ...; |
259 |
* } |
260 |
* }}</pre> |
261 |
* |
262 |
* Here, the call to {@code reachabilityFence} is nonintuitively |
263 |
* placed <em>after</em> the call to {@code update}, to ensure that |
264 |
* the array slot is not nulled out by {@link Object#finalize} before |
265 |
* the update, even if the call to {@code action} was the last use of |
266 |
* this object. This might be the case if for example a usage in a |
267 |
* user program had the form {@code new Resource().action();} which |
268 |
* retains no other reference to this Resource. While probably |
269 |
* overkill here, {@code reachabilityFence} is placed in a {@code |
270 |
* finally} block to ensure that it is invoked across all paths in the |
271 |
* method. In a method with more complex control paths, you might |
272 |
* need further precautions to ensure that {@code reachabilityFence} |
273 |
* is encountered along all of them. |
274 |
* |
275 |
* <p>It is sometimes possible to better encapsulate use of |
276 |
* {@code reachabilityFence}. Continuing the above example, if it |
277 |
* were OK for the call to method update to proceed even if the |
278 |
* finalizer had already executed (nulling out slot), then you could |
279 |
* localize use of {@code reachabilityFence}: |
280 |
* |
281 |
* <pre> {@code |
282 |
* public void action2() { |
283 |
* // ... |
284 |
* Resource.update(getExternalResource()); |
285 |
* } |
286 |
* private ExternalResource getExternalResource() { |
287 |
* ExternalResource ext = externalResourceArray[myIndex]; |
288 |
* Fences.reachabilityFence(this); |
289 |
* return ext; |
290 |
* }}</pre> |
291 |
* |
292 |
* <p>Method {@code reachabilityFence} is not required in |
293 |
* constructions that themselves ensure reachability. For example, |
294 |
* because objects that are locked cannot in general be reclaimed, it |
295 |
* would suffice if all accesses of the object, in all methods of |
296 |
* class Resource (including {@code finalize}) were enclosed in {@code |
297 |
* synchronized (this)} blocks. (Further, such blocks must not include |
298 |
* infinite loops, or themselves be unreachable, which fall into the |
299 |
* corner case exceptions to the "in general" disclaimer.) However, |
300 |
* method {@code reachabilityFence} remains a better option in cases |
301 |
* where this approach is not as efficient, desirable, or possible; |
302 |
* for example because it would encounter deadlock. |
303 |
* |
304 |
* <p><b>Formal Properties.</b> |
305 |
* |
306 |
* <p>Using the terminology of The Java Language Specification chapter |
307 |
* 17, the rules governing the semantics of the methods of this class |
308 |
* are as follows: |
309 |
* |
310 |
* <p>The following is still under construction. |
311 |
* |
312 |
* <dl> |
313 |
* |
314 |
* <dt><b>[Definitions]</b> |
315 |
* <dd> |
316 |
* <ul> |
317 |
* |
318 |
* <li>Define <em>sequenced(a, b)</em> to be true if <em>a</em> |
319 |
* occurs before <em>b</em> in <em>program order</em>. |
320 |
* |
321 |
* <li>Define <em>accesses(a, p)</em> to be true if |
322 |
* <em>a</em> is a read or write of a field (or if an array, an |
323 |
* element) of the object referenced by <em>p</em>. |
324 |
* |
325 |
* <li>Define <em>deeplyAccesses(a, p)</em> to be true if either |
326 |
* <em>accesses(a, p)</em> or <em>deeplyAccesses(a, q)</em> where |
327 |
* <em>q</em> is the value seen by some read <em>r</em> |
328 |
* such that <em>accesses(r, p)</em>. |
329 |
* |
330 |
* </ul> |
331 |
* <dt><b>[Matching]</b> |
332 |
* <dd>Given: |
333 |
* |
334 |
* <ul> |
335 |
* |
336 |
* <li><em>p</em>, a reference to an object |
337 |
* |
338 |
* <li><em>wf</em>, an invocation of {@code orderWrites(p)} or |
339 |
* {@code orderAccesses(p)} |
340 |
* |
341 |
* <li><em>w</em>, a write of value <em>p</em> |
342 |
* |
343 |
* <li><em>rf</em>, an invocation of {@code orderReads(p)} or |
344 |
* {@code orderAccesses(p)} |
345 |
* |
346 |
* <li><em>r</em>, a read returning value <em>p</em> |
347 |
* |
348 |
* </ul> |
349 |
* If: |
350 |
* <ul> |
351 |
* <li>sequenced(wf, w) |
352 |
* <li>read <em>r</em> sees write <em>w</em> |
353 |
* <li>sequenced(r, rf) |
354 |
* </ul> |
355 |
* Then: |
356 |
* <ul> |
357 |
* |
358 |
* <li><em>wf happens-before rf</em> |
359 |
* |
360 |
* <li><em>wf</em> precedes <em>rf</em> in the |
361 |
* <em>synchronization order</em> |
362 |
* |
363 |
* <li>If (<em>r1</em>, <em>w1</em>) and (<em>r2</em>, |
364 |
* <em>w2</em>) are two pairs of reads and writes, both |
365 |
* respectively satisfying the above conditions for <em>p</em>, |
366 |
* and sequenced(r1, r2) then it is not the case that <em>w2 |
367 |
* happens-before w1</em>. |
368 |
* |
369 |
* </ul> |
370 |
* <dt><b>[Initial Reads]</b> |
371 |
* <dd>Given: |
372 |
* |
373 |
* <ul> |
374 |
* |
375 |
* <li><em>p</em>, a reference to an object |
376 |
* |
377 |
* <li><em>a</em>, an access where deeplyAccesses(a, p) |
378 |
* |
379 |
* <li><em>wf</em>, an invocation of {@code orderWrites(p)} or |
380 |
* {@code orderAccesses(p)} |
381 |
* |
382 |
* <li><em>w</em>, a write of value <em>p</em> |
383 |
* |
384 |
* <li><em>r</em>, a read returning value <em>p</em> |
385 |
* |
386 |
* <li><em>b</em>, an access where accesses(b, p) |
387 |
* |
388 |
* </ul> |
389 |
* If: |
390 |
* <ul> |
391 |
* <li>sequenced(a, wf); |
392 |
* <li>sequenced(wf, w) |
393 |
* <li>read <em>r</em> sees write <em>w</em>, and |
394 |
* <em>r</em> is the first read by some thread |
395 |
* <em>t</em> that sees value <em>p</em> |
396 |
* <li>sequenced(r, b) |
397 |
* </ul> |
398 |
* Then: |
399 |
* <ul> |
400 |
* <li>the effects of <em>b</em> are constrained |
401 |
* by the relation <em>a happens-before b</em>. |
402 |
* </ul> |
403 |
* <dt><b>[orderAccesses]</b> |
404 |
* <dd>Given: |
405 |
* |
406 |
* <ul> |
407 |
* <li><em>p</em>, a reference to an object |
408 |
* <li><em>f</em>, an invocation of {@code orderAccesses(p)} |
409 |
* </ul> |
410 |
* If: |
411 |
* <ul> |
412 |
* <li>sequenced(f, w) |
413 |
* </ul> |
414 |
* |
415 |
* Then: |
416 |
* |
417 |
* <ul> |
418 |
* |
419 |
* <li><em>f</em> is an element of the <em>synchronization order</em>. |
420 |
* |
421 |
* </ul> |
422 |
* <dt><b>[Reachability]</b> |
423 |
* <dd>Given: |
424 |
* |
425 |
* <ul> |
426 |
* |
427 |
* <li><em>p</em>, a reference to an object |
428 |
* |
429 |
* <li><em>f</em>, an invocation of {@code reachabilityFence(p)} |
430 |
* |
431 |
* <li><em>a</em>, an access where accesses(a, p) |
432 |
* |
433 |
* <li><em>b</em>, an action (by a garbage collector) taking |
434 |
* the form of an invocation of {@code |
435 |
* p.finalize()} or of enqueuing any {@link |
436 |
* java.lang.ref.Reference} constructed with argument <em>p</em> |
437 |
* |
438 |
* </ul> |
439 |
* |
440 |
* If: |
441 |
* <ul> |
442 |
* <li>sequenced(a, f) |
443 |
* </ul> |
444 |
* |
445 |
* Then: |
446 |
* |
447 |
* <ul> |
448 |
* |
449 |
* <li><em>a happens-before b</em>. |
450 |
* |
451 |
* </ul> |
452 |
* |
453 |
* </dl> |
454 |
* |
455 |
* @since 1.7 |
456 |
* @author Doug Lea |
457 |
*/ |
458 |
public class Fences { |
459 |
private Fences() {} // Non-instantiable |
460 |
|
461 |
/** |
462 |
* The methods of this class are intended to be intrinisified by a |
463 |
* JVM. However, we provide correct but inefficient Java-level |
464 |
* code that simply reads and writes a static volatile |
465 |
* variable. Without JVM support, the consistency effects are |
466 |
* stronger than necessary, and the memory contention effects can |
467 |
* be a serious performance issue. |
468 |
*/ |
469 |
private static volatile int theVolatile; |
470 |
|
471 |
/** |
472 |
* Informally: Ensures that a read of the given reference prior to |
473 |
* the invocation of this method occurs before a subsequent use of |
474 |
* the given reference with the effect of reading or writing a |
475 |
* field (or if an array, element) of the referenced object. The |
476 |
* use of this method is sensible only when paired with other |
477 |
* invocations of {@link #orderWrites} and/or {@link |
478 |
* #orderAccesses} for the given reference. For details, see the |
479 |
* class documentation for this class. |
480 |
* |
481 |
* @param ref the reference. If null, this method has no effect. |
482 |
* @param <T> the type of the reference |
483 |
* @return the given ref, to simplify usage |
484 |
*/ |
485 |
public static <T> T orderReads(T ref) { |
486 |
int ignore = theVolatile; |
487 |
return ref; |
488 |
} |
489 |
|
490 |
/** |
491 |
* Informally: Ensures that a use of the given reference with the |
492 |
* effect of reading or writing a field (or if an array, element) |
493 |
* of the referenced object, prior to the invocation of this |
494 |
* method occur before a subsequent write of the reference. For |
495 |
* details, see the class documentation for this class. |
496 |
* |
497 |
* @param ref the reference. If null, this method has no effect. |
498 |
* @param <T> the type of the reference |
499 |
* @return the given ref, to simplify usage |
500 |
*/ |
501 |
public static <T> T orderWrites(T ref) { |
502 |
theVolatile = 0; |
503 |
return ref; |
504 |
} |
505 |
|
506 |
/** |
507 |
* Informally: Ensures that accesses (reads or writes) using the |
508 |
* given reference prior to the invocation of this method occur |
509 |
* before subsequent accesses. For details, see the class |
510 |
* documentation for this class. |
511 |
* |
512 |
* @param ref the reference. If null, this method has no effect. |
513 |
* @param <T> the type of the reference |
514 |
* @return the given ref, to simplify usage |
515 |
*/ |
516 |
public static <T> T orderAccesses(T ref) { |
517 |
theVolatile = 0; |
518 |
return ref; |
519 |
} |
520 |
|
521 |
/** |
522 |
* Ensures that the object referenced by the given reference |
523 |
* remains <em>strongly reachable</em> (as defined in the {@link |
524 |
* java.lang.ref} package documentation), regardless of any prior |
525 |
* actions of the program that might otherwise cause the object to |
526 |
* become unreachable; thus, the referenced object is not |
527 |
* reclaimable by garbage collection at least until after the |
528 |
* invocation of this method. Invocation of this method does not |
529 |
* itself initiate garbage collection or finalization. |
530 |
* |
531 |
* <p>See the class-level documentation for further explanation |
532 |
* and usage examples. |
533 |
* |
534 |
* @param ref the reference. If null, this method has no effect. |
535 |
*/ |
536 |
public static void reachabilityFence(Object ref) { |
537 |
if (ref != null) { |
538 |
synchronized (ref) {} |
539 |
} |
540 |
} |
541 |
} |