2013年9月15日星期日

volatile instruction reordering problem

package org.volatiles;

import java.io.IOException;
import java.util.Properties;

/**
 * volatile禁止指令重排序优化
 * 
 * @author Byron
 * 
 */
public class VolatileTest2 {

boolean initialized = false;
String name;
String age;
String sex;

public static void main(String[] args) {
VolatileTest2 test = new VolatileTest2();
test.start();
}

public void start() {
Thread t1 = new Thread(new GetProperties());
Thread t2 = new Thread(new UseProperties());
t1.start();
t2.start();

}
/**
 * 获取文件中的属性信息
 * @author Byron
 *
 */
class GetProperties implements Runnable {
@Override
public void run() {
Properties p = new Properties();
try {
p.load(getClass().getResourceAsStream("test.properties"));
name = p.getProperty("name");
age = p.getProperty("age");
sex = p.getProperty("sex");
initialized = true;// 实验了无数次还是没有出现重排序

} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
 * 读取GetProperties从文件中取出的信息
 * @author Byron
 *
 */
class UseProperties implements Runnable {
@Override
public void run() {
while (!initialized) {
// wait
// System.out.println("wait 1 ms");
}
System.out.println("name is: " + name);
System.out.println("age is: " + age);
System.out.println("sex is: " + sex);
}
}

}

instruction reordering did not occur , and why ?
------ Solution ---------------------------------------- ----
how do you verify ? You see bytecode ?
------ Solution ---------------------------------------- ----
studied . .
------ For reference only ---------------------------------------
should be optimized during operation due to , if instruction reordering , then the output of another thread is the null value

没有评论:

发表评论