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



posted @ 2012-03-21 22:37  lostyue  阅读(2016)  评论(0编辑  收藏  举报