java 单例对象的属性更新同步

设置一个读计数器,每次读取配置信息前,将计数器加1,读完后将计数器减1。只有在读计数器为0时,才能更新数据,同时要阻塞所有读属性的调用。

 1   public class GlobalConfig {
2 private static GlobalConfig instance;
3 private Vector properties = null;
4 private boolean isUpdating = false;
5 private int readCount = 0;
6 private GlobalConfig() {
7 //Load configuration information from DB or file
8 //Set values for properties
9 }
10 private static synchronized void syncInit() {
11 if (instance == null) {
12 instance = new GlobalConfig();
13 }
14 }
15 public static GlobalConfig getInstance() {
16 if (instance==null) {
17 syncInit();
18 }
19 return instance;
20 }
21 public synchronized void update(String p_data) {
22 syncUpdateIn();
23 //Update properties
24 }
25 private synchronized void syncUpdateIn() {
26 while (readCount > 0) {
27 try {
28 wait();
29 } catch (Exception e) {
30 }
31 }
32 }
33 private synchronized void syncReadIn() {
34 readCount++;
35 }
36 private synchronized void syncReadOut() {
37 readCount--;
38 notifyAll();
39 }
40 public Vector getProperties() {
41 syncReadIn();
42 //Process data
43 syncReadOut();
44 return properties;
45 }
46 }
47

另一个方法,就是在更新属性时,直接生成另一个单例对象实例,这个新生成的单例对象实例将从数据库或文件中读取最新的配置信息;然后将这些配置信息直接赋值给旧单例对象的属性

 1   public class GlobalConfig {
2 private static GlobalConfig instance = null;
3 private Vector properties = null;
4 private GlobalConfig() {
5 //Load configuration information from DB or file
6 //Set values for properties
7 }
8 private static synchronized void syncInit() {
9 if (instance = null) {
10 instance = new GlobalConfig();
11 }
12 }
13 public static GlobalConfig getInstance() {
14 if (instance = null) {
15 syncInit();
16 }
17 return instance;
18 }
19 public Vector getProperties() {
20 return properties;
21 }
22 public void updateProperties() {
23 //Load updated configuration information by new a GlobalConfig object
24 GlobalConfig shadow = new GlobalConfig();
25 properties = shadow.getProperties();
26 }
27 }
28



转载于:https://www.cnblogs.com/lostyue/archive/2012/03/21/2410749.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值