`
yznxing
  • 浏览: 367348 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

mapMaker使用后记

    博客分类:
  • java
阅读更多

在上一篇使用   google Collection的MapMaker

的时候,提到了一个demo。

接下来做了一个修改,记录下其中的现象。

import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Function;
import com.google.common.collect.MapMaker;

/**
 * @author guoliang created GoogleColTestMain.java
 * @since 2010-4-28 下午05:48:55
 */
public class GoogleColTestMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
    	/**
    	 * softKeys
    	 * weakValues
    	 * 可以设置key跟value的strong,soft,weak属性。不错不错。
    	 * expiration(3, TimeUnit.SECONDS)设置超时时间为3秒
    	 * 
    	 */
        ConcurrentMap<Integer, String> testMap = new MapMaker().concurrencyLevel(32).softKeys().weakValues().expiration(
                3, TimeUnit.SECONDS).makeComputingMap(new Function<Integer, String>() {
            /**
             * 这里就是绑定的根据key没找到value的时候触发的function,
             * 可以将这里的返回值放到对应的key的value中!
             * @param arg0
             * @return
             */
            @Override
            public String apply(Integer arg0) {
                return "create:" + arg0;
            }

        });

        testMap.put(new Integer(1), "hello 1 value");
        
        System.out.println(testMap.get(new Integer(1)));
    }

}

 


    这里可以看到输入的结果是:

create:1

 

   说明map里面没有找到这个key。究其原因查了下mapMaker的api,中间有这样一段话:

 

softKeys

public MapMaker softKeys()

    Specifies that each key (not value) stored in the map should be wrapped in a SoftReference (by default, strong references are used).

    Note: the map will use identity (==) comparison to determine equality of soft keys, which may not behave as you expect. For example, storing a key in the map and then attempting a lookup using a different but equals-equivalent key will always fail.

    Throws:
        IllegalStateException - if the key strength was already set
    See Also:
        SoftReference

 


   对于softKeys在map查找的时候,比较用的是“==”,而不是equals方法,从而导致了刚才找不到的情况!

   把softKeys去掉,使用默认的strongKeys就可以找到了。


   搞完这个事情,接下来,就对soft,weak进行了一下了解,以前只是有看到过这些,但是没怎么理解,最近学习了下。


   参见下篇:weak,soft,phtom Reference,软,弱,虚引用!

 

 

 

 

 

 

0
1
分享到:
评论
2 楼 yznxing 2010-05-12  
RednaxelaFX 写道
其实一直有人抱怨着玩儿的softKeys无法指定比较方式。有时候我们需要的就是equals而不是==。诶。或许以后的版本会有改进的,这地方。



恩。。因为这个我就吧softKeys给去掉了。。。
换成默认的了,悲剧。。。

1 楼 RednaxelaFX 2010-05-12  
其实一直有人抱怨着玩儿的softKeys无法指定比较方式。有时候我们需要的就是equals而不是==。诶。或许以后的版本会有改进的,这地方。

相关推荐

Global site tag (gtag.js) - Google Analytics