Posted on 2007-11-28 22:35
蜀山兆孨龘 閱讀(356)
評論(0) 編輯 收藏
我對 Java 關鍵字 Synchronized 的新理解 |
My New Understanding of Java's Synchronized Keyword |
說實話,我對 Java 并發編程知之不多。我曾經常用關鍵字 volatile 試圖“強制原子操作”,結果帶來的麻煩比解決的還多。Sun Java 教程中的并發課程我以前從沒看完過,現在該通讀一遍了。 |
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. |
我其實知道并經常看到關鍵字 synchronized 的使用,但直到昨天我還沒發覺就這個字消除了很多同步問題。然而,真正的答案在我第一次看這個教程時就在里面了,到這次才弄清。 |
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. |
每個對象都關聯有一個內部鎖,也被稱作監視器鎖或簡稱監視器。當一個線程調用一個同步方法時,它自動請求此方法的內部鎖,并在方法返回時釋放。即使是未捕獲的異常造成了返回,也會發生鎖的釋放。而對靜態同步方法,方法所在類的 Class 對象的內部鎖被請求。同步語句的內部行為沒什么兩樣,只是還需要顯示指定一個需要請求其內部鎖的任意對象。 |
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 關鍵字是鎖定對象的簡單方式,也有很多局限。java.util.concurrency.locks 包支持更高深的鎖定用法,也是我將要學的。 |
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.
|