package com.oldratlee.fucking.concurrency;

import java.util.Random;

/**
 * @author Jerry Lee (oldratlee at gmail dot com)
 */
public class InvalidCombinationStateDemo {
    public static void main(String[] args) {
        CombinationStatTask task = new CombinationStatTask();
        Thread thread = new Thread(task);
        thread.start();

        Random random = new Random();
        while (true) {
            task.state1 = random.nextInt(1000);
            task.state2 = task.state1 * 2;
        }
    }

    private static class CombinationStatTask implements Runnable {
        // 对于组合状态，加 volatile 不能解决问题
        volatile int state1;
        volatile int state2;

        @Override
        public void run() {
            int c = 0;
            for (long i = 0; ; i++) {
                int i1 = state1;
                int i2 = state2;
                if (i1 * 2 != i2) {
                    c++;
                    System.err.printf("Fuck! Got invalid CombinationStat!! check time=%s, happen time=%s(%s%%), count value=%s|%s\n",
                            i + 1, c, (float) c / (i + 1) * 100, i1, i2);
                } else {
                    // 如果去掉这个输出，则在我的开发机上，发生无效组合的概率由 ~15% 降到 ~0.1%
                    System.out.printf("Emm... %s|%s\n", i1, i2);
                }
            }
        }
    }

}

@@ -411,27 +411,24 @@
         
-task.state1
+int rand
  = rando
@@ -466,19 +466,37 @@
 sk.state
-2
+1
  =
+ rand;%0A           
  task.st
@@ -498,17 +498,24 @@
 sk.state
-1
+2 = rand
  * 2;%0A  
@@ -1211,17 +1211,16 @@
 %E7%BB%84%E5%90%88%E7%9A%84%E6%A6%82%E7%8E%87%E7%94%B1 ~
-1
 5%25 %E9%99%8D%E5%88%B0 ~0

use local var, minish critical section. Yes, this can NOT eliminate problem