Skip to main content
 首页 » 编程设计

Java多线程并行计算(Google的Guava使用)

2022年07月18日182leader

参考:https://blog.csdn.net/u011001084/article/details/104037805

结论:参考文章的性能测出的结果 与我实际测试出的结果正好相反, 所以开发还是要实测为准。

添加依赖:

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>

基本用法:
 
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { 
    Cache<String,String> cache1 =CacheBuilder.newBuilder() 
            .expireAfterWrite(3,TimeUnit.SECONDS) // 若缓存项在给定的时间内没有被写访问,则回收(延时回收)。 
            .expireAfterAccess(3,TimeUnit.SECONDS) // 若缓存项在给定的实际内没有被读访问,则回收(延时回收)。 
            .weakValues() // 弱引用存储值,可垃圾回收 
            .weakKeys() // 弱引用存储键,可垃圾回收 
            .concurrencyLevel(8) // 并发级别,指同时支持写缓存的线程数 
            .initialCapacity(10)  // 初始化容量 
            .maximumSize(2000) // 最大存储上限,超过按照LRU算法移除缓存项 
            .recordStats()  // 统计缓存的命中率 
            .removalListener(new MyListener()) // 缓存的移除监听(监听到的是新值) 
            .build(); 
    cache1.put("myKey","myValue"); 
    System.out.println("获取值:" + cache1.getIfPresent("myKey")); 
 
    cache1.invalidate("myKey"); 
    System.out.println("获取我的key:" + cache1.get("myKey",()->"操作数据库")); 
 
    Thread.sleep(5000); 
    System.out.println("再次获取:" + cache1.get("myKey",()->"再次操作数据库")); 
 
    cache1.put("myKey11","myValue11"); // 自然的过期,并不会触发监听 
    Thread.sleep(5000); 
    System.out.println(cache1.getIfPresent("myKey11")); 
    System.in.read(); 
} 
 
private static class MyListener implements RemovalListener<String,String>{ 
    @Override 
    public void onRemoval(RemovalNotification<String, String> notification) { 
        System.out.println("修改的key:" + notification.getKey()); 
        System.out.println("修改的值:" + notification.getValue()); 
        System.out.println("修改的原因:" + notification.getCause()); 
    } 
} 
 
以下是线程池的性能测试: 
// Future的性能测试 
public static void main(String[] args) { 
    ExecutorService executor = Executors.newCachedThreadPool(); 
    long startTime = System.currentTimeMillis(); 
    GuavaMain guavaMain = new GuavaMain(); 
 
    List<Future<String>> futureList = Arrays.asList(executor.submit(() -> guavaMain.test1()), 
            executor.submit(() -> guavaMain.test2()), 
            executor.submit(() -> guavaMain.test3()), 
            executor.submit(() -> guavaMain.test4())); 
    List<String> collect = futureList.stream().map(future -> { 
        try { 
            return future.get(); 
        } catch (InterruptedException e) { 
            e.printStackTrace(); 
        } catch (ExecutionException e) { 
            e.printStackTrace(); 
        } 
        return null; 
    }).collect(Collectors.toList()); 
 
 
    System.out.println("耗时:" + (System.currentTimeMillis() - startTime)); 
} 
 
// CompletableFuture性能测试 
public static void main4(String[] args) { 
    ExecutorService executor = Executors.newCachedThreadPool(); 
    long startTime = System.currentTimeMillis(); 
    GuavaMain guavaMain = new GuavaMain(); 
    List<CompletableFuture<String>> futures = new ArrayList<>(4); 
    futures.add(CompletableFuture.supplyAsync(() -> guavaMain.test1(),executor)); 
    futures.add(CompletableFuture.supplyAsync(() -> guavaMain.test2(),executor)); 
    futures.add(CompletableFuture.supplyAsync(() -> guavaMain.test3(),executor)); 
    futures.add(CompletableFuture.supplyAsync(() -> guavaMain.test4(),executor)); 
 
    CompletableFuture<Void> allFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[4])); 
    CompletableFuture<List<String>> listCompletableFuture = allFuture.thenApplyAsync(value -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()), executor); 
    List<String> join = listCompletableFuture.join(); 
 
    System.out.println("耗时:" + (System.currentTimeMillis() - startTime)); 
} 
 
//  guava性能测试 
public static void main5(String[] args) throws ExecutionException, InterruptedException { 
    ExecutorService executor = Executors.newCachedThreadPool(); 
    ListeningExecutorService guavaExecutor = MoreExecutors.listeningDecorator(executor); 
 
    long startTime = System.currentTimeMillis(); 
    GuavaMain guavaMain = new GuavaMain(); 
    ListenableFuture<String> lf1 = guavaExecutor.submit(() -> guavaMain.test1()); 
    ListenableFuture<String> lf2 = guavaExecutor.submit(() -> guavaMain.test2()); 
    ListenableFuture<String> lf3 = guavaExecutor.submit(() -> guavaMain.test3()); 
    ListenableFuture<String> lf4 = guavaExecutor.submit(() -> guavaMain.test4()); 
 
    ListenableFuture<List<String>> listListenableFuture = Futures.allAsList(lf1, lf2, lf3, lf4); 
    List<String> strings = listListenableFuture.get(); 
 
 
    System.out.println("耗时:" + (System.currentTimeMillis() - startTime)); 
} 
 
private String test1(){ 
    try { 
        Thread.sleep(5000); 
    } catch (InterruptedException e) { 
        e.printStackTrace(); 
    } 
    return "test1"; 
} 
 
private String test2(){ 
    try { 
        Thread.sleep(5000); 
    } catch (InterruptedException e) { 
        e.printStackTrace(); 
    } 
    return "test2"; 
} 
 
private String test3(){ 
    try { 
        Thread.sleep(5000); 
    } catch (InterruptedException e) { 
        e.printStackTrace(); 
    } 
    return "test3"; 
} 
 
private String test4(){ 
    try { 
        Thread.sleep(5000); 
    } catch (InterruptedException e) { 
        e.printStackTrace(); 
    } 
    return "test4"; 
}

本文参考链接:https://www.cnblogs.com/maohuidong/p/15566758.html