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 ...
随机推荐
- WPF上下滚动字幕
XAML代码: <local:WorkSpaceContent x:Class="SunCreate.CombatPlatform.Client.NoticeMarquee" ...
- SQL server 添加主外键约束
---添加主键约束 alter table 表名 add constraint 约束名 primary key (主键) - --添加唯一约束 alter table 表名 ...
- C# 收银机顾显(客显)及打印小票(58热敏打印机)
最近做winform收银机,设计顾显及打印小票总结. 1.顾显(串口COM1) 只涉及到总计,所以只是简单的功能. public static ClientDisplayResult Display( ...
- 微信浏览器禁止app下载链接的两种处理方法
最近替朋友放一个微信下载链接,通过二维码扫描下载. 通过扫描二维码下载APP已成为一个非常方便的方式,微信也成为扫描二维码重要的工具,但是扫描后微信浏览器会对APK和appStore的链接进行屏蔽,导 ...
- Sphinx全文检索
全文检索 一.生活中的数据总体分为: 结构化数据:指具有固定格式或有限长度的数据,如数据库,元数据等. 非结构化数据:指没有固定格式或不定长的数据,如邮件,word文档等. 非结构化数据还有一种叫法: ...
- H - Birthday Paradox (生日悖论)
点击打开链接 Sometimes some mathematical results are hard to believe. One of the common problems is the bi ...
- 【OCP|052】OCP最新题库解析系列-3
3.Which structure can span multiple data files?❑ A) a permanent tablespace❑ B) a bigfile tablespace❑ ...
- 【文文殿下】【HAOI2008】硬币购物
题目描述 硬币购物一共有4种硬币.面值分别为c1,c2,c3,c4.某人去商店买东西,去了tot次.每次带di枚ci硬币,买si的价值的东西.请问每次有多少种付款方法. 数据规模 di,s<=1 ...
- mangodb的存储
mongodb基本命令 mongo #进入mongo命令行show dbs #查看所有数据库 use tutorial #切换到名为tutorial的数据库 show collections #查看数 ...
- 「工具」三分钟了解一款在线流程绘制工具:Whimsical
Whimsical 是一款在线流程绘制工具,只需要一个浏览器就随时随地绘制精美的流程图.除了流程图(Flowcharts)功能,官方还推出了线框图(Wireframes).便利贴(Sticky Not ...