Guava库

9 篇文章 0 订阅
1 篇文章 0 订阅

Guava是Google提供的JAVA拓展类库,其对JDK原生类库进行了拓展和优化。实现了很多实用的新功能和数据结构,且优化了很多JDK已有方法,大大提高了执行效率。一些相同功能,在相同情况对比JDK8的原生方法,都有明显的速度优势。

一 集合容器

1.1 集合常用处理

集合的相应处理主要由Guava提供的Lists,Sets,Maps,Collections2等工具类中静态方法实现。

1.1.1 交并差集合

//Set类型 (set1,set2 <Integer>)
Sets.SetView<Integer> inter=Sets.intersection(set1,set2); //交集
Sets.SetView<Integer> diff=Sets.difference(set1,set2); //差集,在A中不在B中
Sets.SetView<Integer> union=Sets.union(set1,set2); //并集
System.out.println(union);

//Map类型
Maps.difference(mapA,mapB):MapDifference;

1.1.2 集合过滤

guava的过滤非常快,看源码其思路是为原list生成一个包装器,而不是真正过滤list。

包装器包装了list的get/set等方法...在方法中判断值是否满足过滤条件。

//过滤list中满足条件的,input是list中的每一个元素
List<String> list;
Collection<String> f= Collections2.filter(list, input -> {return input.startsWith("h");});

//Map过滤值
Map<Integer,Integer> map1=Maps.filterValues(map, input -> {return input.intValue()==1;});

//Map过滤键
Map<String,Integer> map1=Maps.filterKeys(map, input -> {return input.startsWith("a");});

//Map过滤Entriy
Map<String,String> map1=Maps.filterEntries(map,input -> {
              return input.getValue().equals("1") && input.getKey().startsWith("a");
            });

1.1.3 MapMaker  

Map 构造工具

它可以用来构造ConcurrentHashMap

ConcurrentMap<String, Object> mapAll = new MapMaker() 
    .concurrencyLevel(8) //并发级别 并发级别是指可以同时写缓存的线程数
    .weakKeys()          //弱引用key
    .weakValues()        //弱引用value
    .initialCapacity(20)
    .makeMap();

1.1.4 CacheBuilder

强大的缓存构建工具,build构建的Cache接口对象,也实现了jdk的ConcurrentMap接口,其实现数据结构类似JDK1.7的ConcurrentHashMap

说明:https://www.jianshu.com/p/c8532617773e

使用案例:https://www.cnblogs.com/csonezp/p/10011031.html

Cache<Object, Object> cache = CacheBuilder.newBuilder()
                .concurrencyLevel(10)
                .expireAfterAccess(10, TimeUnit.MINUTES) //统一TTL,超时没有读写操作则清除
                //TTL采用惰性删除,即在get时判断过期
                .initialCapacity(500)
                .maximumSize(1000)  //设置缓存最大容量为1000,超过1000之后就会按照LRU最近虽少使用算法来移除缓存项
                .weakKeys()
                .weakValues()
                .recordStats()  //开启统计功能
                 //设置缓存的移除通知
                .removalListener(new RemovalListener<Object, Object>() {
                    @Override
                    public void onRemoval(RemovalNotification<Object, Object> notification) {
                        System.out.println(notification.getKey() + " 被移除了,原因: " + notification.getCause());
                    }
                })
                //build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
                .build(
                        new CacheLoader<String, User>() {
                            @Override
                            public User load(String key) throws Exception {
                                System.out.println("缓存没有时,从数据库加载" + key);
                                return new User("tony" + key, key);
                            }
                        }
                );

//没有缓存执行Callable获取,底层防止击穿设计:一个线程执行提前暴露future,其他线程future.get等待
Object o = cache.get("1", ()->{return getValue();});

//开启统计功能后
cache.hitRate();                 //缓存命中率;
cache.averageLoadPenalty();      //加载新值的平均时间,单位为纳秒;
cache.evictionCount();           //缓存项被回收的总数,不包括显式清除。
cache.cleanup();                 //手动强制清除过期缓存,默认过期使用懒清除模式,

二、令牌桶限流RateLimiter

https://www.jianshu.com/p/8f548e469bbe

@Service
public class AccessLimitService {

    //每秒只发出5个令牌
    RateLimiter rateLimiter = RateLimiter.create(5.0);

    /**
     * 尝试获取令牌
     * @return
     */
    public boolean tryAcquire(){
        return rateLimiter.tryAcquire();
    }
}

三 各种数据结构

https://blog.csdn.net/kuyuyingzi/article/details/30529053

https://www.jianshu.com/p/b76d4f8d0544

 

四 Monitor代替synchronized+wait

https://www.cnblogs.com/hupengcool/p/4250903.html

1、支持多条件wait   

2、避免了循环wait的代码操作。

繁琐的传统操作:

     持锁->循环判断条件wait->...放锁

     持锁->notify->放锁

五 Collections2 

https://zhuanlan.zhihu.com/p/22840990

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值