I'm trying to reproduce a memory visibility issue in case of insufficient object initialization for non-final fields (JLS 17.5 Final Field Semantics, FinalFieldExample class example). Where it stated "However, f.y is not final; the reader() method is therefore not guaranteed to see the value 4 for it"
I've tried this code:
public class ReorderingTest2 {
public static void main(String[] args) {
for (int i = 0; i < 2500; i++) {
new Thread(new Reader(i)).start();
new Thread(new Writer(i)).start();
}
}
static class Reader implements Runnable {
private String name;
Reader(int i) {
this.name = "reader" + i;
}
@Override
public void run() {
//System.out.println(name + " started");
while (true) {
FinalFieldExample.reader(name);
}
}
}
static class Writer implements Runnable {
private String name;
Writer(int i) {
this.name = "writer" + i;
}
@Override
public void run() {
//System.out.println(name + " started");
while (true) {
FinalFieldExample.writer();
}
}
}
static class FinalFieldExample {
int x;
int y;
static FinalFieldExample f;
public FinalFieldExample() {
x = 3;
y = 4;
}
static void writer() {
f = new FinalFieldExample();
}
static void reader(String name) {
if (f != null) {
int i = f.x;
int j = f.y;
if (i != 3 || j != 4) {
System.out.printf("reader %s sees it!%n", name);
}
}
}
}
}
As in previous my similar topic - I've tried on different PCs (from 2 to 8 cores) with Windows and even on our server-side Solaris 32 core box - I couldn't reproduce it: f.x and f.y - are always already proper-initialized.
For Intel/x86/x64 architecture as I got the answer - they have pretty much default memery guarantees which prevent such constructor logic reordering. Seems the same is true for Solaris/sparc too?
So in what architecture/OSes this reordering can be reproduced?
Alpha. Paul E. McKenney's book Is Parallel Programming Hard, And, If So, What Can You Do About It? has a chapter explaining thememory model of the most important platforms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With