yet*_*der 5 java concurrency multithreading memory-visibility
在编写一些java文章时,我试图在多线程环境中的非同步对象构造的情况下重现重新排序.构建重型对象时没有同步/挥发性/韵母和其他线程在构造函数调用后立即访问它的情况.这是我尝试的代码:
public class ReorderingTest {
static SomeObject<JPanel>[] sharedArray = new SomeObject[100];
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
String name = "watcher" + i;
new Thread(new Watcher(name)).start();
System.out.printf("watcher %s started!%n", name);
}
}
static class Watcher implements Runnable {
private String name;
Watcher(String name) {
this.name = name;
}
public void run() {
while (true) {
int randomIndex = (int) (Math.random() * sharedArray.length);
SomeObject<JPanel> item = sharedArray[randomIndex];
if (item == null) {
//System.out.printf("sharedArray[%s]=null%n", randomIndex);
double r = 1 + Math.random() * 1000;
sharedArray[randomIndex] = new SomeObject<JPanel>(
new JPanel(), UUID.randomUUID().toString(), r, (float)r * 33, (long)r);
} else {
//System.out.printf("sharedArray[%s]=<obj>!%n", randomIndex);
if (item.value == null ||
(item.stringField == null) ||
(item.doubleField == 0) ||
(item.floatField == 0) ||
(item.longField == 0)
) {
System.err.printf("watcher %s sees default values: %s!%n", name, item);
} else {
// fully initialized! run new construction process
double r = 1 + Math.random() * 1000;
sharedArray[randomIndex] = new SomeObject<JPanel>(
new JPanel(), UUID.randomUUID().toString(), r, (float)r * 37, (long)r);
}
}
/*try {
TimeUnit.NANOSECONDS.sleep(randomIndex);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}*/
}
}
}
static class SomeObject<V> {
V value;
String stringField;
double doubleField;
float floatField;
long longField;
SomeObject(V value, String stringField, double doubleField, float floatField, long longField) {
this.value = value;
this.stringField = stringField;
this.doubleField = doubleField;
this.floatField = floatField;
this.longField = longField;
}
@Override
public String toString() {
return "SomeObject{" +
"value=" + value == null ? "null" : "<obj>" +
", stringField='" + stringField + '\'' +
", doubleField=" + doubleField +
", floatField=" + floatField +
", longField=" + longField +
'}';
}
}
}
Run Code Online (Sandbox Code Playgroud)
- 但到目前为止没有效果,我尝试了不同的2,4和8核心Intel/AMD PC与Windows,运行测试几个小时 - 没有重新排序效果 - System.err.printf("观察者%s看到.. .") - 未调用,static sharedArray [randomIndex]引用始终包含完全构造的值.
怎么了?如何重现这个?
这是一篇不错的文章,应该展示 x86 上的重新排序(这是一项壮举,因为 x86 内存模型几乎“安全”):
http://bartoszmilewski.wordpress.com/2008/11/05/who-ordered-memory-fences-on-an-x86/
您的示例不会显示重新排序。编译器不会重新排序为“分配后但构造前存储对象引用”,因为构造函数可能会抛出异常,因此需要恢复引用。由于给定的保证,某些处理器可能会重新排序,但没有英特尔兼容的处理器。
| 归档时间: |
|
| 查看次数: |
664 次 |
| 最近记录: |