guava快速入门(三)
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快速入门(三)的更多相关文章
- Guava快速入门
Guava快速入门 Java诞生于1995年,在这20年的时间里Java已经成为世界上最流行的编程语言之一.虽然Java语言时常经历各种各样的吐槽,但它仍然是一门在不断发展.变化的语言--除了语言本身 ...
- guava快速入门(一)
Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] .缓存 [caching] .原生类型支持 [primitives support] ...
- Mysql快速入门(三)
MySQL性能优化之查看执行计划explain 介绍: (1).MySQL 提供了一个 EXPLAIN 命令, 它可以对 SELECT 语句进行分析, 并输出 SELECT 执行的详细信息, 以供开发 ...
- guava快速入门(二)
Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] .缓存 [caching] .原生类型支持 [primitives support] ...
- Linux Bash Shell快速入门 (三)
forfor 循环结构与 C 语言中有所不同,在 BASH 中 for 循环的基本结构是: for $var in dostatmentsdone 其中 $var 是循环控制变量, 是 $var 需要 ...
- Ant快速入门(三)-----定义生成文件
适应Ant的关键就是编写生成文件,生成文件定义了该项目的各个生成任务(以target来表示,每个target表示一个生成任务),并定义生成任务之间的依赖关系. Ant生成文件的默认名为build.xm ...
- jquery快速入门三
事件 常用事件 click(function(){.......}) #触发或将函数绑定到指定元素的click事件 hover(function(){.....}) 当鼠标指针悬停在上面时触发.... ...
- Solr.NET快速入门(三)【高亮显示】
此功能会"高亮显示"匹配查询的字词(通常使用标记),包括匹配字词周围的文字片段. 要启用高亮显示,请包括HighlightingParameters QueryOptions对象, ...
- Dubbo快速入门 三
3.dubbo环境搭建 3.1).[windows]-安装zookeeper 1.下载zookeeper 网址 https://archive.apache.org/dist/zookeeper/zo ...
随机推荐
- NPOI设置Excel单元格字体、边框、对齐、背景色
代码: ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.BorderBottom = BorderStyle.Thin; ce ...
- css细节复习笔记——内边距、边框和外边距
一个元素的内边距.边框和外边距属性会影响着整个文档如何布局,更重要的是,它们会严重影响给定元素的外观. 高度和宽度 这两个属性不能应用到行内非替换元素,其高度和宽度由链接的内容确定,而不是由创作人员确 ...
- RPC 简单小试
由于经常被抓取文章内容,在此附上博客文章网址:,偶尔会更新某些出错的数据或文字,建议到我博客地址 : --> 点击这里 RPC是指远程过程调用,也就是说两台服务器A,B,一个应用部署在A服务器 ...
- LOJ#6047. 「雅礼集训 2017 Day10」决斗(set)
题面 传送门 题解 这么简单一道题我考试的时候居然只打了\(40\)分暴力? 如果我们把每个点的\(a_i\)记为\(deg_i-1\),其中\(deg_i\)表示有\(deg_i\)个数的\(A_i ...
- winform两个窗体之间传值(C#委托事件实现)
委托 定义一个委托,声明一个委托变量,然后让变量去做方法应该做的事. 委托是一个类型 事件是委托变量实现的 经典例子:两个winform窗体传值 定义两个窗体:form1和form2 form1上有一 ...
- 认识CSS中精灵技术(sprite)和滑动门
前端之HTML,CSS(十) 精灵技术与精灵图 精灵技术本质 精灵技术是一种处理网页背景图像的方式,实质是将小的背景图片拼接到一张大的背景图像上.拼接成的大图被称为精灵图.浏览器打开网页时,每一个图片 ...
- 七,OpenERP 移库操作模块
整个代码中比较关键的地方是如何统计出不同库位的产品数量.
- Mac 10.12安装PDF浏览工具Foxit Reader
说明:永久没费的跨平台PDF浏览工具. 下载: (链接: https://pan.baidu.com/s/1pLEAoXH密码: is5j)
- Mac下使用Wine安装正则表达式工具RegexBuddy 4
下载: (链接: https://pan.baidu.com/s/1bzRae6 密码: b5d3) 安装: 1.安装Wine 参考:http://www.cnblogs.com/EasonJim/p ...
- Mac下像Windows那样带有预览图的快速切换-HyperSwitch
这东西是免费的,他家还出了一个HyperDock的收费软件. 下载:https://bahoom.com/hyperswitch/get 离线版本:(链接: https://pan.baidu.com ...