guava快速入门(三)

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

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

 

目录
相关文章
|
JavaScript 前端开发 程序员
做为前端面试官,春招跳槽建议你把这20个vue题目搞懂
做为前端面试官,春招跳槽建议你把这20个vue题目搞懂
218 0
|
安全 NoSQL Shell
Linux下缓冲区溢出攻击的原理及对策
前言 从逻辑上讲进程的堆栈是由多个堆栈帧构成的,其中每个堆栈帧都对应一个函数调用。当函数调用发生时,新的堆栈帧被压入堆栈;当函数返回时,相应的堆栈帧从堆栈中弹出。
1338 0
|
6天前
|
数据采集 人工智能 安全
|
16天前
|
云安全 监控 安全
|
2天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:七十、小树成林,聚沙成塔:随机森林与大模型的协同进化
随机森林是一种基于决策树的集成学习算法,通过构建多棵决策树并结合它们的预测结果来提高准确性和稳定性。其核心思想包括两个随机性:Bootstrap采样(每棵树使用不同的训练子集)和特征随机选择(每棵树分裂时只考虑部分特征)。这种方法能有效处理大规模高维数据,避免过拟合,并评估特征重要性。随机森林的超参数如树的数量、最大深度等可通过网格搜索优化。该算法兼具强大预测能力和工程化优势,是机器学习中的常用基础模型。
265 155
|
3天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:六十九、Bootstrap采样在大模型评估中的应用:从置信区间到模型稳定性
Bootstrap采样是一种通过有放回重抽样来评估模型性能的统计方法。它通过从原始数据集中随机抽取样本形成多个Bootstrap数据集,计算统计量(如均值、标准差)的分布,适用于小样本和非参数场景。该方法能估计标准误、构建置信区间,并量化模型不确定性,但对计算资源要求较高。Bootstrap特别适合评估大模型的泛化能力和稳定性,在集成学习、假设检验等领域也有广泛应用。与传统方法相比,Bootstrap不依赖分布假设,在非正态数据中表现更稳健。
205 105