您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在singleton中对synchronized的使用

2025/6/5 18:43:39发布28次查看
最近在看java方向的一些东西, 笔者这些年在c, php, java等面向对象的语言的使用中,有一些自己的体会。 语言是没有好坏的, 只有使用的场合的合适与否。 没有哪种语言说是可以完全取代别的语言的。 java从出现到现在风靡全球, 有他道理的。 想的有点多的,
最近在看java方向的一些东西, 笔者这些年在c++, php, java等面向对象的语言的使用中,有一些自己的体会。
语言是没有好坏的, 只有使用的场合的合适与否。 没有哪种语言说是可以完全取代别的语言的。
java从出现到现在风靡全球, 有他道理的。
想的有点多的, 本文主要是针对在现在的项目中一个同事写的singleton模式对synchronized使用的一些自己的理解。
先上他写的code,
public class dbconnpool{ private static dbconnpool instance = null; public synchronized static dbconnpool getinstance() { if (instance == null) { try { string modbase = system.getenv(dm_home); modbase = modbase != null ? modbase : .; string dbcfg = modbase + file.separator + conf + file.separator + dbcfg.xml; instance = new dbconnpool(dbcfg); } catch (exception e) { log.fatal(create connection pool instance failed, e); } } return instance; }}
java synchronized详解。笔者比较推荐使用synchronized 块而不是synchronized  方法。
public class singleton{private static volatile singleton _instance;public static singleton getinstance(){ if(_instance == null){ synchronized(singleton.class){ if(_instance == null) _instance = new singleton(); } } return _instance;}
这样的话, 在多线程环境中, 对getinstance的访问就不会被blocked, 而是仅当_instance为null时, 需要创建时, 才要block其他的线程。
这样可以提高系统的效率。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product