詭異的java.lang.IllegalMonitorStateException

來源:互聯網
上載者:User

今天的一段代碼拋出了java.lang.IllegalMonitorStateException,代碼如下:

private boolean wait = false;public boolean pleaseWait() {synchronized (this.wait) {if (this.wait == true) {return false;}this.wait =true;try {this.wait.wait();} catch (InterruptedException e) {}return true;}

JavaDoc上關於IllegalMonitorStateException的解釋是:

Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

看起來有些晦澀難懂,比如object's monitor。其實,在Object.notify()這個函數的JavaDoc中有相關的解釋:

A thread becomes the owner of the object's monitor in one of three ways:
1. By executing a synchronized instance method of that object.
2. By executing the body of a synchronized statement that synchronizes on the object.
3. For objects of type Class, by executing a synchronized static method of that class. 

說白了,就是需要在調用wait()或者notify()之前,必須使用synchronized語義綁定住被wait/notify的對象。

可問題是,在上面的代碼中,已經對this.wait這個變數使用了synchronzied,然後才調用的this.wait.wait()。按理不應該拋出這個異常。

上網查了很久,終於找到了答案:

真正的問題在於this.wait這個變數是一個Boolean,並且,在調用this.wait.wait()之前,this.wait執行了一次賦值操作:

this.wait = true;

Boolean型變數在執行指派陳述式的時候,其實是建立了一個新的對象。簡單的說,在指派陳述式的之前和之後,this.wait並不是同一個對象。

synchronzied(this.wait)綁定的是舊的Boolean對象,而this.wait.wait()使用的是新的Boolean對象。由於新的Boolean對象並沒有使用synchronzied進行同步,所以系統拋出了IllegalMonitorStateException異常。

相同的悲劇還有可能出現在this.wait是Integer或者String類型的時候。

一個解決方案是採用java.util.concurrent.atomic中對應的類型,比如這裡就應該是AtomicBoolean。採用AtomicBoolean類型,可以保證對它的修改不會產生新的對象。

正確的代碼:

private AtomicBoolean wait = new AtomicBoolean(false);public boolean pleaseWait() {synchronized (this.wait) {if (this.wait.get() == true) {return false;}this.wait.set(true);try {this.wait.wait();} catch (InterruptedException e) {}return true;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.