开发者

Technique of using volatile flag as replacement to locking

开发者 https://www.devze.com 2023-02-09 18:13 出处:网络
Recently, I came across a volatile flag technique, which I may avoid from using synchronized or lock.

Recently, I came across a volatile flag technique, which I may avoid from using synchronized or lock.

http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html

Here is one of the code example of using volatile flag.

Correct Working Example

Thread 1
========
// re-odering will not happen. initialize_var...
// will not move below "volatile_initialization_ready = true"
// statement.
initialize_var1();
initialize_var2();
initialize_var3();
volatile_initialization_ready = true;


Thread 2
========
if (volatile_initialization_ready) {
    use_var1();
    use_var2();
    use_var3();
}

However, I find out I just can't use this technique in certain situation as follow.

Wrong Working Example

Thread 1
========
volatile_going_to_destroy = true;
destroy_var1();
destroy_var2();
destroy_var3();

Thread 2
========
if (volati开发者_Python百科le_going_to_destroy) {
    return;    // ignore.
}

// But Thread 1 still able to perform destroy
// when Thread 2 halt right here. Also, re-ordering might
// happen, where destroy_var1 might move above 
// "volatile_going_to_destroy = true" statement.
use_var1();
use_var2();
use_var3();

I was wondering, is it possible for me to make Wrong Working Example work, but just using volatile, without using synchronized or lock?


volatile only solves the visibility problem. You still need locks for synchronization.


You can use an algorithm like the following http://en.wikipedia.org/wiki/Dekker%27s_algorithm. It allows for safe variable access with only memory barriers but without locks.

0

精彩评论

暂无评论...
验证码 换一张
取 消