My new understanding of Java's "synchronized" keyword
Posted on 2007-11-28 22:35 蜀山兆孨龘 閱讀(365) 評(píng)論(0) 編輯 收藏我對(duì) Java 關(guān)鍵字 Synchronized 的新理解 | My New Understanding of Java's Synchronized Keyword |
說實(shí)話,我對(duì) Java 并發(fā)編程知之不多。我曾經(jīng)常用關(guān)鍵字 volatile 試圖“強(qiáng)制原子操作”,結(jié)果帶來的麻煩比解決的還多。Sun Java 教程中的并發(fā)課程我以前從沒看完過,現(xiàn)在該通讀一遍了。 | To be honest, I knew only a little about concurrent programming in Java. I uesed to use keyword volatile as an attempt to "enforce atomic operations" which had brought me more troubles than solved. Time to walk through the Concurrency Trail of Sun's Java Tutorials that I never finished reading in the past. |
我其實(shí)知道并經(jīng)常看到關(guān)鍵字 synchronized 的使用,但直到昨天我還沒發(fā)覺就這個(gè)字消除了很多同步問題。然而,真正的答案在我第一次看這個(gè)教程時(shí)就在里面了,到這次才弄清。 | I do know and often see the usage of keyword synchronized, but until yesterday I hadn't figured out how thie single word elimated so many synchronization problems. However, the very answer lies in those tutorials ever since I first read it and this time it has been clearly understood. |
每個(gè)對(duì)象都關(guān)聯(lián)有一個(gè)內(nèi)部鎖,也被稱作監(jiān)視器鎖或簡(jiǎn)稱監(jiān)視器。當(dāng)一個(gè)線程調(diào)用一個(gè)同步方法時(shí),它自動(dòng)請(qǐng)求此方法的內(nèi)部鎖,并在方法返回時(shí)釋放。即使是未捕獲的異常造成了返回,也會(huì)發(fā)生鎖的釋放。而對(duì)靜態(tài)同步方法,方法所在類的 Class 對(duì)象的內(nèi)部鎖被請(qǐng)求。同步語句的內(nèi)部行為沒什么兩樣,只是還需要顯示指定一個(gè)需要請(qǐng)求其內(nèi)部鎖的任意對(duì)象。 |
Every boject has an intrinsic lock, which is also known as monitor lock or monitor for short, associated with it. When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception. As for a static synchronized method, an intrinsic lock for the Class object of that method's Class is acquired instead. Synchronized statements internally behaves no differently except in addition to this, an arbitrary object whose intrinsic lock will be acquired can be and should be explicitly specified. |
總之,synchronized 關(guān)鍵字是鎖定對(duì)象的簡(jiǎn)單方式,也有很多局限。java.util.concurrency.locks 包支持更高深的鎖定用法,也是我將要學(xué)的。 |
In conclusion, synchronized keyword is a simplified way of locking objects, and also has many limitations. More sophisticated locking idioms are supported by the java.util.concurrency.locks package which I am going to learn. |