Multithreaded Correctness: Using a Synchronized Block

I use the CMU Sphinx Voice Recognizer library ( Source Link ), which uses some blocks synchronized.

One sample block from RecognizerTask:

Event mailbox;

[...]

public void start() {
    synchronized (this.mailbox) {
        this.mailbox.notifyAll();
        this.mailbox = Event.START;
    }
}

The code works without problems, however BugFinder gives this warning:

Error: Sync on RecognizerTask.mailbox in a vain attempt to guard it

This method is synchronized in the field in what seems to be trying to protect against simultaneous updates in this field. But field protection receives a lock on the specified object, not on the field. This may not provide the mutual exception that you need, and other threads may receive locks on reference objects (for other purposes). An example of this pattern might be:

private Long myNtfSeqNbrCounter = new Long(0);
private Long getNotificationSequenceNumber() {
     Long result = null;
     synchronized(myNtfSeqNbrCounter) {
         result = new Long(myNtfSeqNbrCounter.longValue() + 1);
         myNtfSeqNbrCounter = new Long(result.longValue());
     }
     return result;
 }

, , . ? , ?

/edit: , Event.wait():

Event todo = Event.NONE;
        synchronized (this.mailbox) {
            todo = this.mailbox;
            /* If we're idle then wait for something to happen. */
            if (state == State.IDLE && todo == Event.NONE) {
                try {
                    //Log.d(getClass().getName(), "waiting");
                    this.mailbox.wait();
                    todo = this.mailbox;
                    //Log.d(getClass().getName(), "got" + todo);
                } catch (InterruptedException e) {
                    /* Quit main loop. */
                    //Log.e(getClass().getName(), "Interrupted waiting for mailbox, shutting down");
                    todo = Event.SHUTDOWN;
                }
            }
            /* Reset the mailbox before releasing, to avoid race condition. */
            this.mailbox = Event.NONE;
        }

synchronized. ?

+5
2

, . notifyAll(), , - wait():

synchronized (this.mailbox) {
    this.mailbox.wait();        
}

, , .

, , :

this.mailbox = Event.START;

, , this.mailbox, . , , :

  • this.mailbox .

.

+3

"" , , mailbox. mailbox, , "" , .

, , !

[]:

synchronised (myObject) { 
  myObject = new Object();
  i += 5; //assume i is an instance variable
}

! , !

+3

All Articles