0

http://en.wikipedia.org/wiki/Double_checked_locking_pattern#Usage_in_Java中使用局部变量作为优化,来自 Joshua Bloch “Effective Java, Second Edition”,p。283 使其在“某些版本的 Java VM”上速度提高 25%。当相关变量也是静态的时,这种局部变量的好处是否适用,它是否适用于Android?

那么这些getInstance()s 中的哪一个在 Android 上更快(或者它们是否相同?):

A:

class Something {

    private static volatile Something instance = null;

    public static Something getInstance(Context context) {
        Something local = instance;
        if (local==null) {
            synchronized(Something.class) {
                local = instance;
                if (local==null) {
                    instance = local = new Something(context);
                }
            }
        }
        return local;
    }
}

或者

B.

class Something {

    private static volatile Something instance = null;

    public static Something getInstance(Context context) {
        if (instance==null) {
            synchronized(Something.class) {
                if (instance == null) {
                    instance = new Something(context);
                }
            }
        }
        return instance;
    }
}

为什么?

(别担心,Something不保留对 的引用context,它只是在需要它进行实例化时临时使用它,这就是为什么我似乎需要实例化是“懒惰的”。)

如果你的答案是“只是测试它”,你能给我这样做的步骤吗?但是,如果有的话,我还是想知道差异的原因(反正可能没有)。

4

1 回答 1

0

我认为最快的方法是跳过仔细检查并使用仍然线程安全的方式:

public final class Foo {
    private static volatile Foo mInstance      = new Foo();

    private Foo() {
        // do what ever you want
    }

    /**
     * @return The singleton object
     */
    public static Foo getInstance() {
        return mInstance;
    }

    /**
     * @return the singleton object with new context
     */
    public static Foo getInstance(Context context) {
        mInstance.setContext(context); // just as an example
        return mInstance;
    }
}
于 2013-03-27T11:59:50.383 回答