1

When I use the code shown below, IntelliJ IDEA tell me "expression expected" in the code DecibelSample. What is that mean, How can I fix it?

if (mDecibelSample == null) {
    synchronized (DecibelSample) { // expression expected
        if (mDecibelSample == null) {
            mDecibelSample = new DecibelSample();
        }
    }
}
ben75
  • 29,217
  • 10
  • 88
  • 134
HalfLike
  • 219
  • 1
  • 2
  • 7

2 Answers2

1

Assuming that DecibelSample is a class, this is not valid Java code.

Modify your code like this in order to get rid of the compile error:

synchronized (DecibelSample.class) {}

Your code won't work because synchronized needs some instance to lock against. In the modified example above it will use the Class instance.

You could also change it to synchronized (this) {} in which case it would use the instance of the class your method is in as the lock.

Third option is to define arbitrary object to use as a lock, for instance like this:

private static final Object LOCK = new Object();

...

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

This would probably be the best approach, since locking against the current instance or class instance has some disadvantages. See this SO answer for more details:

More information about the synchronized keyword can be found in Java Language Specification.

Community
  • 1
  • 1
Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109
1

The synchronized keyword requires an Object. DecibelSample is a classname, not an Object.

The Object will be used to ensure synchronization : i.e. when a thread need to execute the code inside the synchronized block : the thread must acquire a lock on the Object.

  • if the lock can be aquired by the thread then the code inside the block is executed and the lock is released so that another thread can acquire it.

  • if the lock cannot be acquired : the thread wait until the lock (owned by another thread) is released.

In your case, you need an Object to support the locking mechanism:

//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();
            }
        }
    }
ben75
  • 29,217
  • 10
  • 88
  • 134