今天突然理解了“volatile”

首先咱们可以看一下MSDN对volatile的定义:
The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

然后呢,咱们可以看到在Singleton模式中对多线程的优化

 1 using  System;
 2 using  System.Configuration;
 3
 4 namespace  HeadFirstDesignPatterns.Singleton.InterestRate
 5 {
 6    /// <summary>
 7    /// Summary description for RateSingleton.
 8    /// </summary>

 9    public class RateSingleton
10    {
11        private volatile static RateSingleton uniqueInstance;
12        private static object syncRoot = new Object();
13
14        private double currentRate = 
15            Convert.ToDouble(ConfigurationSettings.AppSettings["CurrentInterestRate"]);
16
17        public double CurrentRate
18        {
19            get
20            {
21                return currentRate;
22            }

23            set
24            {
25                currentRate = value;
26            }

27        }

28
29        private RateSingleton()
30        {}
31
32        public static RateSingleton GetInstance()
33        {
34            //The approach below ensures that only one instance is created and only 
35            //when the instance is needed. Also, the uniqueInstance variable is 
36            //declared to be volatile to ensure that assignment to the instance variable 
37            //completes before the instance variable can be accessed. Lastly, 
38            //this approach uses a syncRoot instance to lock on, rather than 
39            //locking on the type itself, to avoid deadlocks.
40
41            if(uniqueInstance == null)
42            {
43                lock (syncRoot)
44                {
45                    if(uniqueInstance == null)
46                    {
47                        uniqueInstance = new RateSingleton();
48                    }

49                }

50            }

51            return uniqueInstance;
52        }

53    }

54}

55
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值