, , - , , , .
, , /JVM . , A :
field1 = "hello";
field2 = "world";
B:
System.out.println(field2);
System.out.println(field1);
, B "", "null" (, field1). , field2 field1 — , field2 , , , field1 ? ! , 2 :
field2 = "world";
field1 = "hello";
( field2 = "world" field1 = "hello", , .) , : - , , , . , .
...
, - ( , final ). -, , -, , -, . , , ( , , ?), - . , foo = new ConcreteFoo():
ConcreteFoo ( this); initalize, -...this.x = xthis.y = yfoo = <the newly constructed object>
, ; B , ( ):
foo = <the newly constructed object, with default values for all fields>foo.getX(), 0this.x = x ( )- (
this.y = y B)
,
. AtomicReference ...
(HB). HB, CPU .
:
- A A
- B - B
- A B
- , B B, , , , A A. , B "" A saw .
, . , , - volatile: HB , , , . , A volatile, B , B A, (, , : B ).
, field2 volatile. :
Thread 1:
field1 = "hello";
field2 = "world";
Thread 2:
System.out.println(field2);
System.out.println(field1);
1 "" HB, 2 ". , 2 2 , 1 1 — , field1 = "hello" ( field2 = "world"). , 2 " world \n hello", .
AtomicReferences
, AtomicReference? javadoc java.util.concurrent.atomic:
, 17.4 Java ™.
, HB myAtomicRef.set myAtomicRef.get. , , myAtomicRef.compareAndSet myAtomicRef.get.
AbstractFoo
AtomicReference AbstractFoo HB. this.x ( initialize, ), this.x ( getX), , getX x ( 0).
AbstractFoo HB: initialize init.set this.x = x, getX init.get ( checkInit), this.x > , ( y). HB, , 2, getX, , this.x, A, initialize, init.set; , 2 this.x = x, return [this.]x.
- , . JLS 17.4.4.
JCIP, Java .