synchronized block:“表达预期”

时间:2014-12-08 15:26:13

标签: java android intellij-idea concurrency

当我使用下面显示的代码时,IntelliJ IDEA会在代码DecibelSample中告诉我“表达式”。这是什么意思,我该如何解决?

if (mDecibelSample == null) {
    synchronized (DecibelSample) { // expression expected
        if (mDecibelSample == null) {
            mDecibelSample = new DecibelSample();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

假设DecibelSample是一个类,这不是有效的Java代码。

修改你的代码,以便摆脱编译错误:

synchronized (DecibelSample.class) {}

您的代码无法正常工作,因为synchronized需要一些实例来锁定。在上面的修改示例中,它将使用Class实例。

您也可以将其更改为synchronized (this) {},在这种情况下,它会使用您的方法所在类的实例作为锁。

第三个选项是定义用作锁的任意对象,例如:

private static final Object LOCK = new Object();

...

public void foo() {
    synchronized(LOCK) {}
}

这可能是最好的方法,因为锁定当前实例或类实例有一些缺点。有关详细信息,请参阅此SO answer

有关synchronized关键字的更多信息,请参阅Java Language Specification

答案 1 :(得分:1)

synchronized关键字需要一个Object。 DecibelSample是一个类名,而不是一个对象。

Object将用于确保同步:即当线程需要执行synchronized块内的代码时:线程必须获取对象的锁定。

  • 如果线程可以获取锁,则执行块内的代码并释放锁,以便另一个线程可以获取它。

  • 如果无法获取锁定:线程等待锁定(由另一个线程拥有)被释放。

在您的情况下,您需要一个Object来支持锁定机制:

//used for locking only
// don't consume useless memory : a zero-sized array is fine
// ensure that the LOCK is shared between all threads : let's make it static
// ensure that the object used for locking cannot be changed by anyone : let's make it final
// at first sight : we don't need to synchronize on this Object in another class : keep it private.
private static final Object[] LOCK = new Object[0];

  ...
    if (mDecibelSample == null) {
        synchronized (LOCK) {
            if (mDecibelSample == null) {
                mDecibelSample = new DecibelSample();
            }
        }
    }