Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] 、字符串处理 [string processing] 、I/O 等等。

guava类似Apache Commons工具集

Cache

缓存在很多场景下都是相当有用的。例如,计算或检索一个值的代价很高,并且对同样的输入需要不止一次获取值的时候,就应当考虑使用缓存。

Guava Cache与ConcurrentMap很相似,但也不完全一样。最基本的区别是ConcurrentMap会一直保存所有添加的元素,直到显式地移除。相对地,Guava Cache为了限制内存占用,通常都设定为自动回收元素。在某些场景下,尽管LoadingCache 不回收元素,它也是很有用的,因为它会自动加载缓存。

Guava Cache是一个全内存的本地缓存实现,它提供了线程安全的实现机制。

通常来说,Guava Cache适用于:

  • 你愿意消耗一些内存空间来提升速度。

  • 你预料到某些键会被查询一次以上。

  • 缓存中存放的数据总量不会超出内存容量。(Guava Cache是单个应用运行时的本地缓存。它不把数据存放到文件或外部服务器。

如果这不符合你的需求,请尝试Memcached这类工具)

Guava Cache有两种创建方式:

  • cacheLoader
  • callable callback

LoadingCache是附带CacheLoader构建而成的缓存实现

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; public class LoadingCacheDemo { public static void main(String[] args) {
LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(100) // 最大缓存数目
.expireAfterAccess(2, TimeUnit.SECONDS) // 缓存1秒后过期
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return key;
}
});
cache.put("j", "java");
cache.put("c", "cpp");
cache.put("s", "scala");
cache.put("g", "go");
try {
System.out.println(cache.get("j"));
TimeUnit.SECONDS.sleep(1);
System.out.println(cache.get("s")); // 1秒后 输出scala
TimeUnit.SECONDS.sleep(2);
System.out.println(cache.get("s")); // 2秒后 输出s } catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
} }

  返回:

java
scala
s

  回调:

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder; public class CallbackDemo { public static void main(String[] args) {
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(100)
.expireAfterAccess(1, TimeUnit.SECONDS)
.build();
try {
String result = cache.get("java", () -> "hello java");
System.out.println(result);
} catch (ExecutionException e) {
e.printStackTrace();
}
} }

  

refresh机制: 
- LoadingCache.refresh(K) 在生成新的value的时候,旧的value依然会被使用。 
- CacheLoader.reload(K, V) 生成新的value过程中允许使用旧的value 
- CacheBuilder.refreshAfterWrite(long, TimeUnit) 自动刷新cache

并发

ListenableFuture

传统JDK中的Future通过异步的方式计算返回结果:在多线程运算中可能或者可能在没有结束返回结果,Future是运行中的多线程的一个引用句柄,确保在服务执行返回一个Result。

ListenableFuture可以允许你注册回调方法(callbacks),在运算(多线程执行)完成的时候进行调用, 或者在运算(多线程执行)完成后立即执行。这样简单的改进,使得可以明显的支持更多的操作,这样的功能在JDK concurrent中的Future是不支持的。

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors; import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors; public class ListenableFutureDemo { public static void main(String[] args) {
// 将ExecutorService装饰成ListeningExecutorService
ListeningExecutorService service = MoreExecutors.
listeningDecorator(Executors.newCachedThreadPool()); // 通过异步的方式计算返回结果
ListenableFuture<String> future = service.submit(() -> {
System.out.println("call execute..");
return "task success!";
}); // 有两种方法可以执行此Future并执行Future完成之后的回调函数
future.addListener(() -> { // 该方法会在多线程运算完的时候,指定的Runnable参数传入的对象会被指定的Executor执行
try {
System.out.println("result: " + future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}, service); Futures.addCallback(future, new FutureCallback<String>() {
@Override
public void onSuccess( String result) {
System.out.println("callback result: " + result);
} @Override
public void onFailure(Throwable t) {
System.out.println(t.getMessage());
}
}, service);
} }

  返回:

call execute..
result: task success!
callback result: task success!

  

IO

import java.io.File;
import java.io.IOException;
import java.util.List; import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files; public class FileDemo { public static void main(String[] args) {
File file = new File(System.getProperty("user.dir"));
System.out.println(file.getName());
System.out.println(file.getPath());
} // 写文件
private void writeFile(String content, File file) throws IOException {
if (!file.exists()) {
file.createNewFile();
}
Files.write(content.getBytes(Charsets.UTF_8), file);
} // 读文件
private List<String> readFile(File file) throws IOException {
if (!file.exists()) {
return ImmutableList.of(); // 避免返回null
}
return Files.readLines(file, Charsets.UTF_8);
} // 文件复制
private void copyFile(File from, File to) throws IOException {
if (!from.exists()) {
return;
}
if (!to.exists()) {
to.createNewFile();
}
Files.copy(from, to);
} }

  返回:

collection-others
D:\GITHUB\java\code\test01\collection-others

  

参考:Google Guava官方教程(中文版) 
guava-importnew

guava快速入门(三)的更多相关文章

  1. Guava快速入门

    Guava快速入门 Java诞生于1995年,在这20年的时间里Java已经成为世界上最流行的编程语言之一.虽然Java语言时常经历各种各样的吐槽,但它仍然是一门在不断发展.变化的语言--除了语言本身 ...

  2. guava快速入门(一)

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] .缓存 [caching] .原生类型支持 [primitives support] ...

  3. Mysql快速入门(三)

    MySQL性能优化之查看执行计划explain 介绍: (1).MySQL 提供了一个 EXPLAIN 命令, 它可以对 SELECT 语句进行分析, 并输出 SELECT 执行的详细信息, 以供开发 ...

  4. guava快速入门(二)

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] .缓存 [caching] .原生类型支持 [primitives support] ...

  5. Linux Bash Shell快速入门 (三)

    forfor 循环结构与 C 语言中有所不同,在 BASH 中 for 循环的基本结构是: for $var in dostatmentsdone 其中 $var 是循环控制变量, 是 $var 需要 ...

  6. Ant快速入门(三)-----定义生成文件

    适应Ant的关键就是编写生成文件,生成文件定义了该项目的各个生成任务(以target来表示,每个target表示一个生成任务),并定义生成任务之间的依赖关系. Ant生成文件的默认名为build.xm ...

  7. jquery快速入门三

    事件 常用事件 click(function(){.......}) #触发或将函数绑定到指定元素的click事件 hover(function(){.....}) 当鼠标指针悬停在上面时触发.... ...

  8. Solr.NET快速入门(三)【高亮显示】

    此功能会"高亮显示"匹配查询的字词(通常使用标记),包括匹配字词周围的文字片段. 要启用高亮显示,请包括HighlightingParameters QueryOptions对象, ...

  9. Dubbo快速入门 三

    3.dubbo环境搭建 3.1).[windows]-安装zookeeper 1.下载zookeeper 网址 https://archive.apache.org/dist/zookeeper/zo ...

随机推荐

  1. .Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

    零.创建一个.Net Core 2.0 的ConsoleApp 应用,建完就是这个样子了. 添加Log4Net 的引用,(不想看可以不看,个人习惯)Install-Package log4net添加C ...

  2. winform 版本号比较

    Version now_v = new Version(strval); Version load_v = new Version(model.version.ToString()); if (now ...

  3. javacript 实现瀑布流原理和效果, 滚动加载图片【图文解析 附源码】

    先科普下瀑布流吧 瀑布流,又称瀑布流式布局.是比较流行的一种网站页面布局,视觉表现为参差不齐的多栏布局,随着页面滚动条向下滚动,这种布局还会不断加载数据块并附加至当前尾部.最早采用此布局的网站是Pin ...

  4. Programmatically Disable Event Firing on List Item Update in SharePoint 2010

    1. Microsoft.SharePoint.dll Create EventFiring.cs 1.Right-click on the project, select Add and click ...

  5. ASP.NET Core使用NLog记录日志

    1.根目录新建nlog.config配置文件 <?xml version="1.0"?> <nlog xmlns="http://www.nlog-pr ...

  6. ceph 移除 osd

    1:从crush中移除节点ceph osd crush remove osd.0 2:删除节点ceph osd rm osd.0 3:删除节点认证(不删除编号会占住)ceph auth del osd ...

  7. NOIP2015BLOCKADE c++ 代码

    #include<algorithm> #include<fstream> #include<functional> #include<iostream> ...

  8. 【FAQ】Maven 本地仓库明明有jar包,pom文件还是报错解决办法

    方法一: 找到出错的jar包文件位置,删掉_maven.repositories文件 方法二: maven中的本地仓库的index索引没有更新导致 解决方案: 在eclipse中打开菜单 window ...

  9. 【Quartz】Spring Boot使用properties文件配置Quartz

    (1)在resource目录下新建quartz.properties文件 #============================================================== ...

  10. js的语言的理解

    1.所谓字面量,就是语言语法 2.在js编译器读到语法时候,执行时候创建对象:在赋值的时候创建一个对象,或者是一个匿名对象. 3.函数定义本身是一个对象:执行时候不产生实例对象:这跟python类不一 ...