再谈Double Check Lock!

03-04-11 shyguy
              

近日模仿了Jive中的Cache,自己做了一个通用的Cache系统。于是牵涉到了一些同步问题。
我发现Jive中好多地方用到了Double Check Lock.
我看了一些相关的文档,应该说DCL是在Java中不成立的。
那么我现在这段代码大家看看,能否使用呢?


/**
* Get object from cache
* @param type object type
* @param key object ID as key in cache
* @return Object
*/

public static Object getObject(Object cacheType,Object key){
Cache cache = (Cache)cacheList.get(cacheType);
if(cache == null){
synchronized(cacheType){
//这里保证cacheType是全局且唯一的
cache = (Cache)cacheList.get(cacheType);
if(cache == null){
cache = new Cache(105,lifeTime);
}
}
}


上面的代码是根据CacheType从一个HashMap中去get()某个Cache。
由于DCL不成立,所以上面的代码无法保证同步
(具体参见http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)

那么,我改动成为这样以后,是否可以了呢?

Class CacheManager{
...
private static Cache reservedCache = new Cache();
......

public static Object getObject(Object type,Object key){

public static Object getObject(Object cacheType,Object key){
Cache cache = (Cache)cacheList.get(cacheType);
if(cache == null){
synchronized(cacheType){ //这里保证cacheType是全局且唯一的
cache = (Cache)cacheList.get(cacheType);
if(cache == null){
cache = reservedCache;
reservedCache = new Cache(105,lifeTime);
}
}
}
}

:)

              

cheng_hx
2003-05-11 13:17

<<java与模式>>中指出dcl在java中不可用。
具体原因没有说太清楚。

Jevang
2003-05-12 23:36

what's the relationship between reserverCache and cachelist in your code? if you later put reserverCache into cachelist at the end of synch block, I guess it's fine as there is no crossing point among threads before that.
Here is another article on DCL:
http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double-p2.html

shyguy
2003-05-13 19:44

> what's the relationship between reserverCache and
> cachelist in your code?
cacheList是一个HashMap,Key是public static final Integer,代表保存Cache的类型,Value是Cache Object.

而Cache内部也用了一个HashMap而已,只不过Cache::get/set同步了而已。

>if you later put
> reserverCache into cachelist at the end of synch
> block, I guess it's fine as there is no crossing
> point among threads before that.
我就在想,引用之间的赋值应该是原子操作的吧?


shyguy
2003-05-13 20:11

这篇文章偶看过了,偶现在就用static singlton。不过不知道如果把我的程序移到了集群的AppServer上以后,会怎么样。。。。好多Singleton的。。。汗ing...

偶要是全部synchronized起来,那么1CPU和4CPU还有什么区别呢?

看起来,用Java写多线程容易,但是要写好也不是那么容易了,基本上已经和用C++处于同一个水平层次咯。或者说和语言差不多无关咯~~~
重要的是要知道点系统结构,汇编咯,否则自己死到那里取都不知道错在咯~~~

4Go 1 2 3 4 下一页