Java : volatile
volatileの効果を確かめるテストというのは難しいな。
次のプログラムは、volatileの有無で差が出なかった。
Javaの場合、JITの後にどういうコードになっているかをみないといけないので、逆アセンブルというのも難しいしな。
public class Test2 { static final int MAX = 10000000; static volatile boolean flag = false; static int count = 0; public static void main (String[] args) throws InterruptedException { Thread ocount = new Count(); Thread oflip = new Flip(); ocount.start(); oflip.start(); ocount.join(); oflip.join(); System.out.println("count="+count); } static class Count extends Thread { public void run () { flag = false; for (int i=0; i<MAX; ++i) if (flag) ++count; } } static class Flip extends Thread { public void run () { for (int i=0; i<MAX; ++i) flag = (i/10)%2==1; } } }