【发布时间】:2012-02-05 22:06:37
【问题描述】:
我正在使用 CMU Sphinx 语音识别器库 (Link to source),它使用了 synchronized 块。
来自 RecognizerTask 的一个示例块:
Event mailbox;
[...]
public void start() {
synchronized (this.mailbox) {
this.mailbox.notifyAll();
this.mailbox = Event.START;
}
}
代码可以正常运行,但是 BugFinder 会发出以下警告:
错误:在 RecognizerTask.mailbox 上进行同步是徒劳的 守护它
这个方法在一个看起来像 试图防止同时更新该字段。但 保护一个字段会锁定被引用的对象,而不是 场地。这可能无法提供您需要的互斥,以及其他 线程可能正在获取被引用对象的锁(对于其他 目的)。这种模式的一个例子是:
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 语句。使用它是否有意义?
【问题讨论】:
标签: java android multithreading synchronized