1

我们都知道 Java 非常彻底地优化了我们的代码,我们都喜欢它。嗯,大多数时候。下面是一段真正让我头疼的代码:

public class BrokenOptimizationTest {

/**
 * This thread constantly polls another thread object's private field.
 */
public static class ComparingThread extends Thread {
    private int currentValue = 0;
    private AdditionThread otherThread = null;

    public ComparingThread(AdditionThread add) {
        this.otherThread = add;
    }

    @Override
    public void run() {
        while (true) {
            int testValue = currentValue;

            if (BrokenOptimizationTest.shouldDoSomething) {

                do {
                    testValue = otherThread.getValue();
                    BrokenOptimizationTest.doSomething();
                    // System.out.println(testValue); // to see testValue really changes
                }
                while (testValue == currentValue);

            }
            else {

                do {
                    testValue = otherThread.getValue();
                    // System.out.println(testValue); // to see testValue really changes
                }
                while (testValue == currentValue);

            }

            System.out.println("{ testValue: " + testValue + ", currentValue: " + currentValue + " }");

            currentValue = testValue;
        }
    }
}

/**
 * This thread often adds to its pollable value.
 */
public static class AdditionThread extends Thread {
    private int currentValue = 0;
    public long queryCount = 0;

    public int getValue() {
        ++queryCount;
        return currentValue;
    }

    @Override
    public void run() {
        while (true) {
            ++currentValue;

            //I said 'often', so sleep some more
            try {
                Thread.sleep(1);
            }
            catch (InterruptedException e) {}
        }
    }
}

/**
 * Whether or not the program must simulate doing an expensive calculation between consecutive queries.
 */
public static boolean shouldDoSomething = false;

/**
 * Simulates doing an expensive calculation
 */
public static void doSomething() {
    try {
        Thread.sleep(0, 100);
    }
    catch (InterruptedException e) {}
}


/**
 * Call the program with something like "slow" to enable doSomething
 */
public static void main(String[] args) {
    if (args.length >= 1 && (args[0].toLowerCase().contains("slow") || args[0].toLowerCase().contains("dosomething")))
        shouldDoSomething = true;


    AdditionThread addThread = new AdditionThread();
    ComparingThread compThread = new ComparingThread(addThread);
    addThread.start();
    compThread.start();

    /**
     * Print the current program state every now and then.
     */
    while (true) {
        System.out.println("{ currentValue: " + addThread.getValue() + ", activeThreads: " + Thread.activeCount() + ", queryCount: " + addThread.queryCount + " }");
        System.out.flush();

        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException e) {}
    }
}
}

结果可能在快速、慢速单线程和多线程处理器之间有所不同。在我测试的计算机上(没有 doSomething),输出如下所示:

{ currentValue: 1, activeThreads: 3, queryCount: 1 }
{ testValue: 1, currentValue: 0 }
{ testValue: 2, currentValue: 1 }
{ testValue: 3, currentValue: 2 }
{ testValue: 4, currentValue: 3 }
{ testValue: 5, currentValue: 4 }
{ testValue: 6, currentValue: 5 }
{ testValue: 7, currentValue: 6 }
{ testValue: 8, currentValue: 7 }
{ testValue: 9, currentValue: 8 }
{ testValue: 10, currentValue: 9 }
{ testValue: 11, currentValue: 10 }
{ testValue: 12, currentValue: 11 }
{ testValue: 13, currentValue: 12 }
{ currentValue: 994, activeThreads: 3, queryCount: 2176924819 }
{ currentValue: 1987, activeThreads: 3, queryCount: 4333727079 }
{ currentValue: 2980, activeThreads: 3, queryCount: 6530688815 }
{ currentValue: 3971, activeThreads: 3, queryCount: 8723797559 }

CompareThread的前几次迭代运行良好,然后 Java 进行“优化”:testValuecurrentValue始终相等并不断更改它们的值,尽管线程从未离开最内层循环。我能想到的唯一原因是Java无序执行,如下所示:

do {
    testValue = otherThread.getValue();
    currentValue = testValue; // moved up from beneath the loop
}
while (testValue == currentValue);

我知道在 Java 编译器中允许乱序执行,因为它可以提高性能,但是这些语句显然是相互依赖的。

我的问题很简单:为什么为什么Java 会以这种方式运行程序?

注意:如果程序以参数 doSomething 启动,或者 AdditionThread.currentValue 设置为volatile,则代码运行良好。

4

1 回答 1

4

您已经回答了自己的问题:

如果 AdditionThread.currentValue 变为 volatile,则代码运行良好。

java 内存模型不保证当您从 ComparingThread 中读取 AdditionThread.currentValue 时,您将看到 AdditionThread 中存在的最新版本。如果数据要对其他线程可见,则必须使用提供的工具之一,volatile、synchronized、java.util.concurrent.*,以便告诉系统您需要可见性保证。

乱序执行不是导致意外行为的优化,它只是 ComparingThread 在自己的堆栈上保留 AdditionThread.currentValue 的副本。

打开“doSomething”也可以修复它,因为让线程进入睡眠状态通常会导致它们在唤醒时刷新堆栈,尽管这并没有正式保证。

于 2013-05-07T20:02:52.210 回答