单例使用
来源:互联网 发布:c语言布尔值 编辑:程序博客网 时间:2024/05/02 01:31
一、单例对象的初始化同步
对于初始化的同步,可以通过如下代码所采用的方式解决。
public class GlobalConfig {
private static GlobalConfig instance = null;
private Vector properties = null;
private GlobalConfig() {
//Load configuration information from DB or file
//Set values for properties
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new GlobalConfig();
}
}
public static GlobalConfig getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
public Vector getProperties() {
return properties;
}
}
这种处理方式虽然引入了同步代码,但是因为这段同步代码只会在最开始的时候执行一次或多次,所以对整个系统的性能不会有影响。
二、单例对象的属性更新同步
单例对象的属性更新同步
为了解决第2个问题,有两种方法:
1,参照读者/写者的处理方式
设置一个读计数器,每次读取配置信息前,将计数器加1,读完后将计数器减1。只有在读计数器为0时,才能更新数据,同时要阻塞所有读属性的调用。代码如下。
public class GlobalConfig {
private static GlobalConfig instance;
private Vector properties = null;
private boolean isUpdating = false;
private int readCount = 0;
private GlobalConfig() {
//Load configuration information from DB or file
//Set values for properties
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new GlobalConfig();
}
}
public static GlobalConfig getInstance() {
if (instance==null) {
syncInit();
}
return instance;
}
public synchronized void update(String p_data) {
syncUpdateIn();
//Update properties
}
private synchronized void syncUpdateIn() {
while (readCount > 0) {
try {
wait();
} catch (Exception e) {
}
}
}
private synchronized void syncReadIn() {
readCount++;
}
private synchronized void syncReadOut() {
readCount--;
notifyAll();
}
public Vector getProperties() {
syncReadIn();
//Process data
syncReadOut();
return properties;
}
}
2,采用"影子实例"的办法
具体说,就是在更新属性时,直接生成另一个单例对象实例,这个新生成的单例对象实例将从数据库或文件中读取最新的配置信息;然后将这些配置信息直接赋值给旧单例对象的属性。如下面代码所示。
public class GlobalConfig {
private static GlobalConfig instance = null;
private Vector properties = null;
private GlobalConfig() {
//Load configuration information from DB or file
//Set values for properties
}
private static synchronized void syncInit() {
if (instance = null) {
instance = new GlobalConfig();
}
}
public static GlobalConfig getInstance() {
if (instance = null) {
syncInit();
}
return instance;
}
public Vector getProperties() {
return properties;
}
public void updateProperties() {
//Load updated configuration information by new a GlobalConfig object
GlobalConfig shadow = new GlobalConfig();
properties = shadow.getProperties();
}
}
摘自:http://yangyiqian.javaeye.com/blog/339606
- 单例使用
- 单例的使用
- 单例使用比较
- 单例的使用
- 单例的使用
- 单例的使用
- C++单例使用
- 使用单枚举类型实现单例
- 单例模式的使用
- 如何使用单例模式
- service 单例的使用
- 使用dispatch_once创建单例
- 单例模式的使用
- 单例模式的使用
- 使用PHP单例模式
- 单例使用的警醒
- 单例模式的使用
- ios-使用单例模式
- 游戏AI引擎的三层体系结构分析
- 八皇后详解
- 在T-SQL中正确使用字符常量以取得最佳性能
- 提升JSP应用程序的七大绝招【转贴】
- 宏定义中的 "#" 和 "##" 的区别
- 单例使用
- 定时执行任务的三种方法
- AjaxPro使用说明
- Office2010抢鲜:Ribbon全面流行 64位首次发布
- S60用户界面控件设计(二)
- Cisco最新安全报告:内部威胁难防 风险评估紧迫
- 虚拟化云计算是硬件厂商的噩梦?!
- 关于MVC
- Flex-DataGrid使用关键字过滤结果