forked from openjdk/valhalla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVarHandle.java
2474 lines (2363 loc) · 110 KB
/
VarHandle.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.invoke;
import java.lang.constant.ClassDesc;
import java.lang.constant.Constable;
import java.lang.constant.ConstantDesc;
import java.lang.constant.ConstantDescs;
import java.lang.constant.DirectMethodHandleDesc;
import java.lang.constant.DynamicConstantDesc;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import jdk.internal.vm.annotation.DontInline;
import jdk.internal.vm.annotation.ForceInline;
import jdk.internal.vm.annotation.IntrinsicCandidate;
import jdk.internal.vm.annotation.Stable;
import static java.lang.invoke.MethodHandleStatics.UNSAFE;
/**
* A VarHandle is a dynamically strongly typed reference to a variable, or to a
* parametrically-defined family of variables, including static fields,
* non-static fields, array elements, or components of an off-heap data
* structure. Access to such variables is supported under various
* <em>access modes</em>, including plain read/write access, volatile
* read/write access, and compare-and-set.
*
* <p>VarHandles are immutable and have no visible state. VarHandles cannot be
* subclassed by the user.
*
* <p>A VarHandle has:
* <ul>
* <li>a {@link #varType variable type} T, the type of every variable referenced
* by this VarHandle; and
* <li>a list of {@link #coordinateTypes coordinate types}
* {@code CT1, CT2, ..., CTn}, the types of <em>coordinate expressions</em> that
* jointly locate a variable referenced by this VarHandle.
* </ul>
* Variable and coordinate types may be primitive or reference, and are
* represented by {@code Class} objects. The list of coordinate types may be
* empty.
*
* <p>Factory methods that produce or {@link java.lang.invoke.MethodHandles.Lookup
* lookup} VarHandle instances document the supported variable type and the list
* of coordinate types.
*
* <p>Each access mode is associated with one <em>access mode method</em>, a
* <a href="MethodHandle.html#sigpoly">signature polymorphic</a> method named
* for the access mode. When an access mode method is invoked on a VarHandle
* instance, the initial arguments to the invocation are coordinate expressions
* that indicate in precisely which object the variable is to be accessed.
* Trailing arguments to the invocation represent values of importance to the
* access mode. For example, the various compare-and-set or compare-and-exchange
* access modes require two trailing arguments for the variable's expected value
* and new value.
*
* <p>The arity and types of arguments to the invocation of an access mode
* method are not checked statically. Instead, each access mode method
* specifies an {@link #accessModeType(AccessMode) access mode type},
* represented as an instance of {@link MethodType}, that serves as a kind of
* method signature against which the arguments are checked dynamically. An
* access mode type gives formal parameter types in terms of the coordinate
* types of a VarHandle instance and the types for values of importance to the
* access mode. An access mode type also gives a return type, often in terms of
* the variable type of a VarHandle instance. When an access mode method is
* invoked on a VarHandle instance, the symbolic type descriptor at the
* call site, the run time types of arguments to the invocation, and the run
* time type of the return value, must <a href="#invoke">match</a> the types
* given in the access mode type. A runtime exception will be thrown if the
* match fails.
*
* For example, the access mode method {@link #compareAndSet} specifies that if
* its receiver is a VarHandle instance with coordinate types
* {@code CT1, ..., CTn} and variable type {@code T}, then its access mode type
* is {@code (CT1 c1, ..., CTn cn, T expectedValue, T newValue)boolean}.
* Suppose that a VarHandle instance can access array elements, and that its
* coordinate types are {@code String[]} and {@code int} while its variable type
* is {@code String}. The access mode type for {@code compareAndSet} on this
* VarHandle instance would be
* {@code (String[] c1, int c2, String expectedValue, String newValue)boolean}.
* Such a VarHandle instance may be produced by the
* {@link MethodHandles#arrayElementVarHandle(Class) array factory method} and
* access array elements as follows:
* <pre> {@code
* String[] sa = ...
* VarHandle avh = MethodHandles.arrayElementVarHandle(String[].class);
* boolean r = avh.compareAndSet(sa, 10, "expected", "new");
* }</pre>
*
* <p>Access modes control atomicity and consistency properties.
* <em>Plain</em> read ({@code get}) and write ({@code set})
* accesses are guaranteed to be bitwise atomic only for references
* and for primitive values of at most 32 bits, and impose no observable
* ordering constraints with respect to threads other than the
* executing thread. <em>Opaque</em> operations are bitwise atomic and
* coherently ordered with respect to accesses to the same variable.
* In addition to obeying Opaque properties, <em>Acquire</em> mode
* reads and their subsequent accesses are ordered after matching
* <em>Release</em> mode writes and their previous accesses. In
* addition to obeying Acquire and Release properties, all
* <em>Volatile</em> operations are totally ordered with respect to
* each other.
*
* <p>Access modes are grouped into the following categories:
* <ul>
* <li>read access modes that get the value of a variable under specified
* memory ordering effects.
* The set of corresponding access mode methods belonging to this group
* consists of the methods
* {@link #get get},
* {@link #getVolatile getVolatile},
* {@link #getAcquire getAcquire},
* {@link #getOpaque getOpaque}.
* <li>write access modes that set the value of a variable under specified
* memory ordering effects.
* The set of corresponding access mode methods belonging to this group
* consists of the methods
* {@link #set set},
* {@link #setVolatile setVolatile},
* {@link #setRelease setRelease},
* {@link #setOpaque setOpaque}.
* <li>atomic update access modes that, for example, atomically compare and set
* the value of a variable under specified memory ordering effects.
* The set of corresponding access mode methods belonging to this group
* consists of the methods
* {@link #compareAndSet compareAndSet},
* {@link #weakCompareAndSetPlain weakCompareAndSetPlain},
* {@link #weakCompareAndSet weakCompareAndSet},
* {@link #weakCompareAndSetAcquire weakCompareAndSetAcquire},
* {@link #weakCompareAndSetRelease weakCompareAndSetRelease},
* {@link #compareAndExchangeAcquire compareAndExchangeAcquire},
* {@link #compareAndExchange compareAndExchange},
* {@link #compareAndExchangeRelease compareAndExchangeRelease},
* {@link #getAndSet getAndSet},
* {@link #getAndSetAcquire getAndSetAcquire},
* {@link #getAndSetRelease getAndSetRelease}.
* <li>numeric atomic update access modes that, for example, atomically get and
* set with addition the value of a variable under specified memory ordering
* effects.
* The set of corresponding access mode methods belonging to this group
* consists of the methods
* {@link #getAndAdd getAndAdd},
* {@link #getAndAddAcquire getAndAddAcquire},
* {@link #getAndAddRelease getAndAddRelease},
* <li>bitwise atomic update access modes that, for example, atomically get and
* bitwise OR the value of a variable under specified memory ordering
* effects.
* The set of corresponding access mode methods belonging to this group
* consists of the methods
* {@link #getAndBitwiseOr getAndBitwiseOr},
* {@link #getAndBitwiseOrAcquire getAndBitwiseOrAcquire},
* {@link #getAndBitwiseOrRelease getAndBitwiseOrRelease},
* {@link #getAndBitwiseAnd getAndBitwiseAnd},
* {@link #getAndBitwiseAndAcquire getAndBitwiseAndAcquire},
* {@link #getAndBitwiseAndRelease getAndBitwiseAndRelease},
* {@link #getAndBitwiseXor getAndBitwiseXor},
* {@link #getAndBitwiseXorAcquire getAndBitwiseXorAcquire},
* {@link #getAndBitwiseXorRelease getAndBitwiseXorRelease}.
* </ul>
*
* <p>Factory methods that produce or {@link java.lang.invoke.MethodHandles.Lookup
* lookup} VarHandle instances document the set of access modes that are
* supported, which may also include documenting restrictions based on the
* variable type and whether a variable is read-only. If an access mode is not
* supported then the corresponding access mode method will on invocation throw
* an {@code UnsupportedOperationException}. Factory methods should document
* any additional undeclared exceptions that may be thrown by access mode
* methods.
* The {@link #get get} access mode is supported for all
* VarHandle instances and the corresponding method never throws
* {@code UnsupportedOperationException}.
* If a VarHandle references a read-only variable (for example a {@code final}
* field) then write, atomic update, numeric atomic update, and bitwise atomic
* update access modes are not supported and corresponding methods throw
* {@code UnsupportedOperationException}.
* Read/write access modes (if supported), with the exception of
* {@code get} and {@code set}, provide atomic access for
* reference types and all primitive types.
* Unless stated otherwise in the documentation of a factory method, the access
* modes {@code get} and {@code set} (if supported) provide atomic access for
* reference types and all primitives types, with the exception of {@code long}
* and {@code double} on 32-bit platforms.
*
* <p>Access modes will override any memory ordering effects specified at
* the declaration site of a variable. For example, a VarHandle accessing
* a field using the {@code get} access mode will access the field as
* specified <em>by its access mode</em> even if that field is declared
* {@code volatile}. When mixed access is performed extreme care should be
* taken since the Java Memory Model may permit surprising results.
*
* <p>In addition to supporting access to variables under various access modes,
* a set of static methods, referred to as memory fence methods, is also
* provided for fine-grained control of memory ordering.
*
* The Java Language Specification permits other threads to observe operations
* as if they were executed in orders different than are apparent in program
* source code, subject to constraints arising, for example, from the use of
* locks, {@code volatile} fields or VarHandles. The static methods,
* {@link #fullFence fullFence}, {@link #acquireFence acquireFence},
* {@link #releaseFence releaseFence}, {@link #loadLoadFence loadLoadFence} and
* {@link #storeStoreFence storeStoreFence}, can also be used to impose
* constraints. Their specifications, as is the case for certain access modes,
* are phrased in terms of the lack of "reorderings" -- observable ordering
* effects that might otherwise occur if the fence was not present. More
* precise phrasing of the specification of access mode methods and memory fence
* methods may accompany future updates of the Java Language Specification.
*
* <h2>Compiling invocation of access mode methods</h2>
* A Java method call expression naming an access mode method can invoke a
* VarHandle from Java source code. From the viewpoint of source code, these
* methods can take any arguments and their polymorphic result (if expressed)
* can be cast to any return type. Formally this is accomplished by giving the
* access mode methods variable arity {@code Object} arguments and
* {@code Object} return types (if the return type is polymorphic), but they
* have an additional quality called <em>signature polymorphism</em> which
* connects this freedom of invocation directly to the JVM execution stack.
* <p>
* As is usual with virtual methods, source-level calls to access mode methods
* compile to an {@code invokevirtual} instruction. More unusually, the
* compiler must record the actual argument types, and may not perform method
* invocation conversions on the arguments. Instead, it must generate
* instructions to push them on the stack according to their own unconverted
* types. The VarHandle object itself will be pushed on the stack before the
* arguments. The compiler then generates an {@code invokevirtual} instruction
* that invokes the access mode method with a symbolic type descriptor which
* describes the argument and return types.
* <p>
* To issue a complete symbolic type descriptor, the compiler must also
* determine the return type (if polymorphic). This is based on a cast on the
* method invocation expression, if there is one, or else {@code Object} if the
* invocation is an expression, or else {@code void} if the invocation is a
* statement. The cast may be to a primitive type (but not {@code void}).
* <p>
* As a corner case, an uncasted {@code null} argument is given a symbolic type
* descriptor of {@code java.lang.Void}. The ambiguity with the type
* {@code Void} is harmless, since there are no references of type {@code Void}
* except the null reference.
*
*
* <h2><a id="invoke">Performing invocation of access mode methods</a></h2>
* The first time an {@code invokevirtual} instruction is executed it is linked
* by symbolically resolving the names in the instruction and verifying that
* the method call is statically legal. This also holds for calls to access mode
* methods. In this case, the symbolic type descriptor emitted by the compiler
* is checked for correct syntax, and names it contains are resolved. Thus, an
* {@code invokevirtual} instruction which invokes an access mode method will
* always link, as long as the symbolic type descriptor is syntactically
* well-formed and the types exist.
* <p>
* When the {@code invokevirtual} is executed after linking, the receiving
* VarHandle's access mode type is first checked by the JVM to ensure that it
* matches the symbolic type descriptor. If the type
* match fails, it means that the access mode method which the caller is
* invoking is not present on the individual VarHandle being invoked.
*
* <p id="invoke-behavior">
* Invocation of an access mode method behaves, by default, as if an invocation of
* {@link MethodHandle#invoke}, where the receiving method handle accepts the
* VarHandle instance as the leading argument. More specifically, the
* following, where {@code {access-mode}} corresponds to the access mode method
* name:
* <pre> {@code
* VarHandle vh = ..
* R r = (R) vh.{access-mode}(p1, p2, ..., pN);
* }</pre>
* behaves as if:
* <pre> {@code
* VarHandle vh = ..
* VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
* MethodHandle mh = MethodHandles.varHandleExactInvoker(
* am,
* vh.accessModeType(am));
*
* R r = (R) mh.invoke(vh, p1, p2, ..., pN)
* }</pre>
* (modulo access mode methods do not declare throwing of {@code Throwable}).
* This is equivalent to:
* <pre> {@code
* MethodHandle mh = MethodHandles.lookup().findVirtual(
* VarHandle.class,
* "{access-mode}",
* MethodType.methodType(R, p1, p2, ..., pN));
*
* R r = (R) mh.invokeExact(vh, p1, p2, ..., pN)
* }</pre>
* where the desired method type is the symbolic type descriptor and a
* {@link MethodHandle#invokeExact} is performed, since before invocation of the
* target, the handle will apply reference casts as necessary and box, unbox, or
* widen primitive values, as if by {@link MethodHandle#asType asType} (see also
* {@link MethodHandles#varHandleInvoker}).
*
* More concisely, such behavior is equivalent to:
* <pre> {@code
* VarHandle vh = ..
* VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
* MethodHandle mh = vh.toMethodHandle(am);
*
* R r = (R) mh.invoke(p1, p2, ..., pN)
* }</pre>
* Where, in this case, the method handle is bound to the VarHandle instance.
*
* <p id="invoke-exact-behavior">
* A VarHandle's invocation behavior can be adjusted (see {@link #withInvokeExactBehavior}) such that invocation of
* an access mode method behaves as if invocation of {@link MethodHandle#invokeExact},
* where the receiving method handle accepts the VarHandle instance as the leading argument.
* More specifically, the following, where {@code {access-mode}} corresponds to the access mode method
* name:
* <pre> {@code
* VarHandle vh = ..
* R r = (R) vh.{access-mode}(p1, p2, ..., pN);
* }</pre>
* behaves as if:
* <pre> {@code
* VarHandle vh = ..
* VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
* MethodHandle mh = MethodHandles.varHandleExactInvoker(
* am,
* vh.accessModeType(am));
*
* R r = (R) mh.invokeExact(vh, p1, p2, ..., pN)
* }</pre>
* (modulo access mode methods do not declare throwing of {@code Throwable}).
*
* More concisely, such behavior is equivalent to:
* <pre> {@code
* VarHandle vh = ..
* VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
* MethodHandle mh = vh.toMethodHandle(am);
*
* R r = (R) mh.invokeExact(p1, p2, ..., pN)
* }</pre>
* Where, in this case, the method handle is bound to the VarHandle instance.
*
* <h2>Invocation checking</h2>
* In typical programs, VarHandle access mode type matching will usually
* succeed. But if a match fails, the JVM will throw a
* {@link WrongMethodTypeException}.
* <p>
* Thus, an access mode type mismatch which might show up as a linkage error
* in a statically typed program can show up as a dynamic
* {@code WrongMethodTypeException} in a program which uses VarHandles.
* <p>
* Because access mode types contain "live" {@code Class} objects, method type
* matching takes into account both type names and class loaders.
* Thus, even if a VarHandle {@code VH} is created in one class loader
* {@code L1} and used in another {@code L2}, VarHandle access mode method
* calls are type-safe, because the caller's symbolic type descriptor, as
* resolved in {@code L2}, is matched against the original callee method's
* symbolic type descriptor, as resolved in {@code L1}. The resolution in
* {@code L1} happens when {@code VH} is created and its access mode types are
* assigned, while the resolution in {@code L2} happens when the
* {@code invokevirtual} instruction is linked.
* <p>
* Apart from type descriptor checks, a VarHandles's capability to
* access its variables is unrestricted.
* If a VarHandle is formed on a non-public variable by a class that has access
* to that variable, the resulting VarHandle can be used in any place by any
* caller who receives a reference to it.
* <p>
* Unlike with the Core Reflection API, where access is checked every time a
* reflective method is invoked, VarHandle access checking is performed
* <a href="MethodHandles.Lookup.html#access">when the VarHandle is
* created</a>.
* Thus, VarHandles to non-public variables, or to variables in non-public
* classes, should generally be kept secret. They should not be passed to
* untrusted code unless their use from the untrusted code would be harmless.
*
*
* <h2>VarHandle creation</h2>
* Java code can create a VarHandle that directly accesses any field that is
* accessible to that code. This is done via a reflective, capability-based
* API called {@link java.lang.invoke.MethodHandles.Lookup
* MethodHandles.Lookup}.
* For example, a VarHandle for a non-static field can be obtained
* from {@link java.lang.invoke.MethodHandles.Lookup#findVarHandle
* Lookup.findVarHandle}.
* There is also a conversion method from Core Reflection API objects,
* {@link java.lang.invoke.MethodHandles.Lookup#unreflectVarHandle
* Lookup.unreflectVarHandle}.
* <p>
* Access to protected field members is restricted to receivers only of the
* accessing class, or one of its subclasses, and the accessing class must in
* turn be a subclass (or package sibling) of the protected member's defining
* class. If a VarHandle refers to a protected non-static field of a declaring
* class outside the current package, the receiver argument will be narrowed to
* the type of the accessing class.
*
* <h2>Interoperation between VarHandles and the Core Reflection API</h2>
* Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup
* Lookup} API, any field represented by a Core Reflection API object
* can be converted to a behaviorally equivalent VarHandle.
* For example, a reflective {@link java.lang.reflect.Field Field} can
* be converted to a VarHandle using
* {@link java.lang.invoke.MethodHandles.Lookup#unreflectVarHandle
* Lookup.unreflectVarHandle}.
* The resulting VarHandles generally provide more direct and efficient
* access to the underlying fields.
* <p>
* As a special case, when the Core Reflection API is used to view the
* signature polymorphic access mode methods in this class, they appear as
* ordinary non-polymorphic methods. Their reflective appearance, as viewed by
* {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
* is unaffected by their special status in this API.
* For example, {@link java.lang.reflect.Method#getModifiers
* Method.getModifiers}
* will report exactly those modifier bits required for any similarly
* declared method, including in this case {@code native} and {@code varargs}
* bits.
* <p>
* As with any reflected method, these methods (when reflected) may be invoked
* directly via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke},
* via JNI, or indirectly via
* {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
* However, such reflective calls do not result in access mode method
* invocations. Such a call, if passed the required argument (a single one, of
* type {@code Object[]}), will ignore the argument and will throw an
* {@code UnsupportedOperationException}.
* <p>
* Since {@code invokevirtual} instructions can natively invoke VarHandle
* access mode methods under any symbolic type descriptor, this reflective view
* conflicts with the normal presentation of these methods via bytecodes.
* Thus, these native methods, when reflectively viewed by
* {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
* <p>
* In order to obtain an invoker method for a particular access mode type,
* use {@link java.lang.invoke.MethodHandles#varHandleExactInvoker} or
* {@link java.lang.invoke.MethodHandles#varHandleInvoker}. The
* {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
* API is also able to return a method handle to call an access mode method for
* any specified access mode type and is equivalent in behavior to
* {@link java.lang.invoke.MethodHandles#varHandleInvoker}.
*
* <h2>Interoperation between VarHandles and Java generics</h2>
* A VarHandle can be obtained for a variable, such as a field, which is
* declared with Java generic types. As with the Core Reflection API, the
* VarHandle's variable type will be constructed from the erasure of the
* source-level type. When a VarHandle access mode method is invoked, the
* types
* of its arguments or the return value cast type may be generic types or type
* instances. If this occurs, the compiler will replace those types by their
* erasures when it constructs the symbolic type descriptor for the
* {@code invokevirtual} instruction.
*
* @see MethodHandle
* @see MethodHandles
* @see MethodType
* @since 9
*/
public abstract sealed class VarHandle implements Constable
permits IndirectVarHandle, LazyInitializingVarHandle, SegmentVarHandle,
VarHandleByteArrayAsChars.ByteArrayViewVarHandle,
VarHandleByteArrayAsDoubles.ByteArrayViewVarHandle,
VarHandleByteArrayAsFloats.ByteArrayViewVarHandle,
VarHandleByteArrayAsInts.ByteArrayViewVarHandle,
VarHandleByteArrayAsLongs.ByteArrayViewVarHandle,
VarHandleByteArrayAsShorts.ByteArrayViewVarHandle,
VarHandleBooleans.Array,
VarHandleBooleans.FieldInstanceReadOnly,
VarHandleBooleans.FieldStaticReadOnly,
VarHandleBytes.Array,
VarHandleBytes.FieldInstanceReadOnly,
VarHandleBytes.FieldStaticReadOnly,
VarHandleChars.Array,
VarHandleChars.FieldInstanceReadOnly,
VarHandleChars.FieldStaticReadOnly,
VarHandleDoubles.Array,
VarHandleDoubles.FieldInstanceReadOnly,
VarHandleDoubles.FieldStaticReadOnly,
VarHandleFloats.Array,
VarHandleFloats.FieldInstanceReadOnly,
VarHandleFloats.FieldStaticReadOnly,
VarHandleInts.Array,
VarHandleInts.FieldInstanceReadOnly,
VarHandleInts.FieldStaticReadOnly,
VarHandleLongs.Array,
VarHandleLongs.FieldInstanceReadOnly,
VarHandleLongs.FieldStaticReadOnly,
VarHandleReferences.Array,
VarHandleReferences.FieldInstanceReadOnly,
VarHandleReferences.FieldStaticReadOnly,
VarHandleShorts.Array,
VarHandleShorts.FieldInstanceReadOnly,
VarHandleShorts.FieldStaticReadOnly,
VarHandleFlatValues.Array,
VarHandleFlatValues.FieldInstanceReadOnly,
VarHandleNonAtomicReferences.Array,
VarHandleNonAtomicReferences.FieldInstanceReadOnly,
VarHandleNonAtomicReferences.FieldStaticReadOnly,
VarHandleNonAtomicFlatValues.Array,
VarHandleNonAtomicFlatValues.FieldInstanceReadOnly {
final VarForm vform;
final boolean exact;
VarHandle(VarForm vform) {
this(vform, false);
}
VarHandle(VarForm vform, boolean exact) {
this.vform = vform;
this.exact = exact;
}
/**
* Returns the target VarHandle. Subclasses may override this method to implement
* additional logic for example lazily initializing the declaring class of a static field var handle.
*/
@ForceInline
VarHandle target() {
return asDirect();
}
/**
* Returns the direct target VarHandle. Indirect VarHandle subclasses should implement
* this method.
*
* @see #getMethodHandle(int)
* @see #checkAccessModeThenIsDirect(AccessDescriptor)
*/
@ForceInline
VarHandle asDirect() {
return this;
}
/**
* Returns {@code true} if this VarHandle has <a href="#invoke-exact-behavior"><em>invoke-exact behavior</em></a>.
*
* @see #withInvokeExactBehavior()
* @see #withInvokeBehavior()
* @return {@code true} if this VarHandle has <a href="#invoke-exact-behavior"><em>invoke-exact behavior</em></a>.
* @since 16
*/
public boolean hasInvokeExactBehavior() {
return exact;
}
// Plain accessors
/**
* Returns the value of a variable, with memory semantics of reading as
* if the variable was declared non-{@code volatile}. Commonly referred to
* as plain read access.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
*
* <p>The symbolic type descriptor at the call site of {@code get}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.GET)} on this VarHandle.
*
* <p>This access mode is supported by all VarHandle instances and never
* throws {@code UnsupportedOperationException}.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn)}
* , statically represented using varargs.
* @return the signature-polymorphic result that is the value of the
* variable
* , statically represented using {@code Object}.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
Object get(Object... args);
/**
* Sets the value of a variable to the {@code newValue}, with memory
* semantics of setting as if the variable was declared non-{@code volatile}
* and non-{@code final}. Commonly referred to as plain write access.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}
*
* <p>The symbolic type descriptor at the call site of {@code set}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.SET)} on this VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T newValue)}
* , statically represented using varargs.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
void set(Object... args);
// Volatile accessors
/**
* Returns the value of a variable, with memory semantics of reading as if
* the variable was declared {@code volatile}.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
*
* <p>The symbolic type descriptor at the call site of {@code getVolatile}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.GET_VOLATILE)} on this
* VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn)}
* , statically represented using varargs.
* @return the signature-polymorphic result that is the value of the
* variable
* , statically represented using {@code Object}.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
Object getVolatile(Object... args);
/**
* Sets the value of a variable to the {@code newValue}, with memory
* semantics of setting as if the variable was declared {@code volatile}.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}.
*
* <p>The symbolic type descriptor at the call site of {@code setVolatile}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.SET_VOLATILE)} on this
* VarHandle.
*
* @apiNote
* Ignoring the many semantic differences from C and C++, this method has
* memory ordering effects compatible with {@code memory_order_seq_cst}.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T newValue)}
* , statically represented using varargs.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
void setVolatile(Object... args);
/**
* Returns the value of a variable, accessed in program order, but with no
* assurance of memory ordering effects with respect to other threads.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
*
* <p>The symbolic type descriptor at the call site of {@code getOpaque}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.GET_OPAQUE)} on this
* VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn)}
* , statically represented using varargs.
* @return the signature-polymorphic result that is the value of the
* variable
* , statically represented using {@code Object}.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
Object getOpaque(Object... args);
/**
* Sets the value of a variable to the {@code newValue}, in program order,
* but with no assurance of memory ordering effects with respect to other
* threads.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}.
*
* <p>The symbolic type descriptor at the call site of {@code setOpaque}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.SET_OPAQUE)} on this
* VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T newValue)}
* , statically represented using varargs.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
void setOpaque(Object... args);
// Lazy accessors
/**
* Returns the value of a variable, and ensures that subsequent loads and
* stores are not reordered before this access.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
*
* <p>The symbolic type descriptor at the call site of {@code getAcquire}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.GET_ACQUIRE)} on this
* VarHandle.
*
* @apiNote
* Ignoring the many semantic differences from C and C++, this method has
* memory ordering effects compatible with {@code memory_order_acquire}
* ordering.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn)}
* , statically represented using varargs.
* @return the signature-polymorphic result that is the value of the
* variable
* , statically represented using {@code Object}.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
Object getAcquire(Object... args);
/**
* Sets the value of a variable to the {@code newValue}, and ensures that
* prior loads and stores are not reordered after this access.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}.
*
* <p>The symbolic type descriptor at the call site of {@code setRelease}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.SET_RELEASE)} on this
* VarHandle.
*
* @apiNote
* Ignoring the many semantic differences from C and C++, this method has
* memory ordering effects compatible with {@code memory_order_release}
* ordering.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T newValue)}
* , statically represented using varargs.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
void setRelease(Object... args);
// Compare and set accessors
/**
* Atomically sets the value of a variable to the {@code newValue} with the
* memory semantics of {@link #setVolatile} if the variable's current value,
* referred to as the <em>witness value</em>, {@code ==} the
* {@code expectedValue}, as accessed with the memory semantics of
* {@link #getVolatile}.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
*
* <p>The symbolic type descriptor at the call site of {@code
* compareAndSet} must match the access mode type that is the result of
* calling {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_SET)} on
* this VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
* , statically represented using varargs.
* @return {@code true} if successful, otherwise {@code false} if the
* <em>witness value</em> was not the same as the {@code expectedValue}.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
* @see #setVolatile(Object...)
* @see #getVolatile(Object...)
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
boolean compareAndSet(Object... args);
/**
* Atomically sets the value of a variable to the {@code newValue} with the
* memory semantics of {@link #setVolatile} if the variable's current value,
* referred to as the <em>witness value</em>, {@code ==} the
* {@code expectedValue}, as accessed with the memory semantics of
* {@link #getVolatile}.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)T}.
*
* <p>The symbolic type descriptor at the call site of {@code
* compareAndExchange}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_EXCHANGE)}
* on this VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
* , statically represented using varargs.
* @return the signature-polymorphic result that is the <em>witness value</em>, which
* will be the same as the {@code expectedValue} if successful
* , statically represented using {@code Object}.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type is not
* compatible with the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type is compatible with the
* caller's symbolic type descriptor, but a reference cast fails.
* @see #setVolatile(Object...)
* @see #getVolatile(Object...)
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
Object compareAndExchange(Object... args);
/**
* Atomically sets the value of a variable to the {@code newValue} with the
* memory semantics of {@link #set} if the variable's current value,
* referred to as the <em>witness value</em>, {@code ==} the
* {@code expectedValue}, as accessed with the memory semantics of
* {@link #getAcquire}.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)T}.
*
* <p>The symbolic type descriptor at the call site of {@code
* compareAndExchangeAcquire}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_EXCHANGE_ACQUIRE)} on
* this VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
* , statically represented using varargs.
* @return the signature-polymorphic result that is the <em>witness value</em>, which
* will be the same as the {@code expectedValue} if successful
* , statically represented using {@code Object}.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
* @see #set(Object...)
* @see #getAcquire(Object...)
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
Object compareAndExchangeAcquire(Object... args);
/**
* Atomically sets the value of a variable to the {@code newValue} with the
* memory semantics of {@link #setRelease} if the variable's current value,
* referred to as the <em>witness value</em>, {@code ==} the
* {@code expectedValue}, as accessed with the memory semantics of
* {@link #get}.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)T}.
*
* <p>The symbolic type descriptor at the call site of {@code
* compareAndExchangeRelease}
* must match the access mode type that is the result of calling
* {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_EXCHANGE_RELEASE)}
* on this VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
* , statically represented using varargs.
* @return the signature-polymorphic result that is the <em>witness value</em>, which
* will be the same as the {@code expectedValue} if successful
* , statically represented using {@code Object}.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
* @see #setRelease(Object...)
* @see #get(Object...)
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
Object compareAndExchangeRelease(Object... args);
// Weak (spurious failures allowed)
/**
* Possibly atomically sets the value of a variable to the {@code newValue}
* with the semantics of {@link #set} if the variable's current value,
* referred to as the <em>witness value</em>, {@code ==} the
* {@code expectedValue}, as accessed with the memory semantics of
* {@link #get}.
*
* <p>This operation may fail spuriously (typically, due to memory
* contention) even if the <em>witness value</em> does match the expected value.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
*
* <p>The symbolic type descriptor at the call site of {@code
* weakCompareAndSetPlain} must match the access mode type that is the result of
* calling {@code accessModeType(VarHandle.AccessMode.WEAK_COMPARE_AND_SET_PLAIN)}
* on this VarHandle.
*
* @param args the signature-polymorphic parameter list of the form
* {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
* , statically represented using varargs.
* @return {@code true} if successful, otherwise {@code false} if the
* <em>witness value</em> was not the same as the {@code expectedValue} or if this
* operation spuriously failed.
* @throws UnsupportedOperationException if the access mode is unsupported
* for this VarHandle.
* @throws WrongMethodTypeException if the access mode type does not
* match the caller's symbolic type descriptor.
* @throws ClassCastException if the access mode type matches the caller's
* symbolic type descriptor, but a reference cast fails.
* @see #set(Object...)
* @see #get(Object...)
*/
public final native
@MethodHandle.PolymorphicSignature
@IntrinsicCandidate
boolean weakCompareAndSetPlain(Object... args);
/**
* Possibly atomically sets the value of a variable to the {@code newValue}
* with the memory semantics of {@link #setVolatile} if the variable's
* current value, referred to as the <em>witness value</em>, {@code ==} the
* {@code expectedValue}, as accessed with the memory semantics of
* {@link #getVolatile}.
*
* <p>This operation may fail spuriously (typically, due to memory
* contention) even if the <em>witness value</em> does match the expected value.
*
* <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
*
* <p>The symbolic type descriptor at the call site of {@code
* weakCompareAndSet} must match the access mode type that is the
* result of calling {@code accessModeType(VarHandle.AccessMode.WEAK_COMPARE_AND_SET)}