Java Thread Programming 1.7 - Concurrent Access to
來源:互聯網
上載者:User
When multiple threads are interacting with an object, controls need to be in place to ensure that the threads don’t adversely affect one another. This chapter deals with issues that can introduce subtle errors in your application. An application that fails to safely control concurrent access can work properly most of the time—maybe nearly all the time—but will occasionally produce erroneous results. This makes the understanding and disciplined use of the information in this chapter critical to writing truly thread-safe applications that work properly all the time.
如果你的系統出現了莫名其妙的問題,很有可能是並發訪問的問題哦
volatile Member Variable Modifier
The Java Language Specification indicates that for optimal speed, individual threads are permitted to keep a working copy of shared member variables and only reconcile them with the shared original occasionally. To be more accurate, the word “occasionally” in the last sentence should be replaced with “when a thread enters or leaves a synchronized block of code.” I’ll tell you more about synchronized blocks later in this chapter. When only one thread is interacting with the member variables of an object, this optimization works very well and can allow for faster execution. When two (or more) threads are simultaneously working with an object, care must be taken to ensure that changes made to a shared member variable by one thread are seen by the other.
Java規範中說明,為了最佳化速度,每個線程都擁有共用成員變數的一個拷貝,當線程開始或結束一個同步代碼塊時,才回寫變數值。當單線程時,這種機制很好的工作,可以獲得更高的效能,但是多個線程協同工作時,必須考慮,被一個線程改變的公開變數要被其他線程知道。
The volatile keyword is used as a modifier on member variables to force individual threads to reread the variable’s value from shared memory every time the variable is accessed. In addition, individual threads are forced to write changes back to shared memory as soon as they occur. This way, two different threads always see the same value for a member variable at any particular time. Chances are that most of you expected this behavior from the Java VM already. In fact, many experienced Java developers don’t understand when the use of volatile is necessary.