玩Java 8 – Lambda和并发

因此Java 8不久前发布,具有许多功能和更改。 我们所有的Java狂热者一直在等待这个历史,从他们最初宣布Java 7的所有强大功能开始一直到最终被取消。

我最近才有时间实际开始给它一个真实的外观,我将我的家庭项目更新到了8个,我不得不说,我对所获得的一切通常感到非常满意。 java.time API的“模仿” JodaTime是一个很大的改进,java.util.stream包正在变得有用,lambda将改变我们的编码样式,这可能需要一些时间来适应这些变化……引用“强大的力量伴随着巨大的责任”这句话是正确的,我认为在我们的未来可能会有一些有趣的时刻,因为编写一些难以破解的代码非常容易。 作为调试示例,我在下面编写的代码将很有趣。

文件示例在我的Github博客回购中

此示例的操作很简单,运行几个线程,并发执行一些工作,然后等待它们全部完成。 我在玩Java 8的时候就想通了,让我全力以赴……
这是我想出的:

package net.briandupreez.blog.java8.futures;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;/*** Generified future running and completion** @param <T> the result type* @param <S> the task input*/
public class WaitingFuturesRunner<T, S> {private transient static final Log logger = LogFactory.getLog(WaitingFuturesRunner.class);private final Collection<Task<T, S>> tasks;private final long timeOut;private final TimeUnit timeUnit;private final ExecutorService executor;/*** Constructor, used to initialise with the required tasks** @param tasks the list of tasks to execute* @param timeOut  max length of time to wait* @param timeUnit     time out timeUnit*/public WaitingFuturesRunner(final Collection<Task<T, S>> tasks, final long timeOut, final TimeUnit timeUnit) {this.tasks = tasks;this.timeOut = timeOut;this.timeUnit = timeUnit;this.executor = Executors.newFixedThreadPool(tasks.size());}/*** Go!** @param taskInput          The input to the task* @param consolidatedResult a container of all the completed results*/public void go(final S taskInput, final ConsolidatedResult<T> consolidatedResult) {final CountDownLatch latch = new CountDownLatch(tasks.size());final List<CompletableFuture<T>> theFutures = tasks.stream().map(aSearch -> CompletableFuture.supplyAsync(() -> processTask(aSearch, taskInput, latch), executor)).collect(Collectors.<CompletableFuture<T>>toList());final CompletableFuture<List<T>> allDone = collectTasks(theFutures);try {latch.await(timeOut, timeUnit);logger.debug("complete... adding results");allDone.get().forEach(consolidatedResult::addResult);} catch (final InterruptedException | ExecutionException e) {logger.error("Thread Error", e);throw new RuntimeException("Thread Error, could not complete processing", e);}}private <E> CompletableFuture<List<E>> collectTasks(final List<CompletableFuture<E>> futures) {final CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));return allDoneFuture.thenApply(v -> futures.stream().map(CompletableFuture<E>::join).collect(Collectors.<E>toList()));}private T processTask(final Task<T, S> task, final S searchTerm, final CountDownLatch latch) {logger.debug("Starting: " + task);T searchResults = null;try {searchResults = task.process(searchTerm, latch);} catch (final Exception e) {e.printStackTrace();}return searchResults;}}

测试:

package net.briandupreez.blog.java8.futures;import net.briandupreez.blog.java8.futures.example.StringInputTask;
import net.briandupreez.blog.java8.futures.example.StringResults;
import org.apache.log4j.BasicConfigurator;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;/*** Test* Created by brian on 4/26/14.*/
public class CompletableFuturesRunnerTest {@BeforeClasspublic static void init() {BasicConfigurator.configure();}/***  5tasks at 3000ms concurrently should not be more than 3100* @throws Exception error*/@Test(timeout = 3100)public void testGo() throws Exception {final List<Task<String, String>> taskList = setupTasks();final WaitingFuturesRunner<String, String> completableFuturesRunner = new WaitingFuturesRunner<>(taskList, 4, TimeUnit.SECONDS);final StringResults consolidatedResults = new StringResults();completableFuturesRunner.go("Something To Process", consolidatedResults);Assert.assertEquals(5, consolidatedResults.getResults().size());for (final String s : consolidatedResults.getResults()) {Assert.assertTrue(s.contains("complete"));Assert.assertTrue(s.contains("Something To Process"));}}private List<Task<String, String>> setupTasks() {final List<Task<String, String>> taskList = new ArrayList<>();final StringInputTask stringInputTask = new StringInputTask("Task 1");final StringInputTask stringInputTask2 = new StringInputTask("Task 2");final StringInputTask stringInputTask3 = new StringInputTask("Task 3");final StringInputTask stringInputTask4 = new StringInputTask("Task 4");final StringInputTask stringInputTask5 = new StringInputTask("Task 5");taskList.add(stringInputTask);taskList.add(stringInputTask2);taskList.add(stringInputTask3);taskList.add(stringInputTask4);taskList.add(stringInputTask5);return taskList;}
}

输出:

0 [pool-1-thread-1] Starting: StringInputTask{taskName='Task 1'}0 [pool-1-thread-5] Starting: StringInputTask{taskName='Task 5'}0 [pool-1-thread-2] Starting: StringInputTask{taskName='Task 2'}2 [pool-1-thread-4] Starting: StringInputTask{taskName='Task 4'}2 [pool-1-thread-3] Starting: StringInputTask{taskName='Task 3'}3003 [pool-1-thread-5] Done: Task 53004 [pool-1-thread-3] Done: Task 33003 [pool-1-thread-1] Done: Task 13003 [pool-1-thread-4] Done: Task 43003 [pool-1-thread-2] Done: Task 23007 [Thread-0] WaitingFuturesRunner  - complete... adding results

在执行此操作时,我发现并阅读了一些有用的文章/链接:

Oracle: Lambda教程

IBM: Java 8并发

Tomasz Nurkiewicz: CompletableFuture权威指南

翻译自: https://www.javacodegeeks.com/2014/04/playing-with-java-8-lambdas-and-concurrency.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/363887.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

用matlab 拟合实数解,求大神指点matlab用拟合的方式解延迟微分方程组参数

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼dy(1)-k*y(1)*y(2);dy(2)Z(3,1)-a*y(2)-q*y(2);dy(3)k*y(1)*y(2)-Z(3,1);dy(4)a*y(2);dy(5)q*y(2);t12345678910111213141516171819202122232425262728293031323334353637383940y208563475657545454535252515150504948484747464545…

AngularJS(三):重复HTML元素、数据绑定

本文也同步发表在我的公众号“我的天空” 重复HTML元素 在前端的页面编写中&#xff0c;我们会经常遇到重复HTML元素&#xff0c;譬如绘制表格、菜单等&#xff0c;如以下代码显示一个简单的li列表&#xff1a; <body> <ul id"ul_cities"> </ul…

hyper-v下的ubuntu虚拟机分辨率修改

修改/etc/default/grub sudo vim /etc/default/grub 改变前: GRUB_CMDLINE_LINUX_DEFAULT"quiet splash" 改变后: GRUB_CMDLINE_LINUX_DEFAULT"quiet splash videohyperv_fb:1920x1080" 更新grub配置 sudo update-grub 重启即可生效 sudo reboot 转载于:ht…

gopacket 在 windows 上面遇到的问题

前阵子有个需求是使用 golang 抓包改包&#xff0c;我用到了 gopacket 这个包&#xff0c;但是出了一些小问题。 我按照网上的方法进行使用 OpenLive 抓包&#xff0c;发现并不行&#xff0c;报错 error open adapter 啥啥啥。 经过调试发现根本找不到这个网卡&#xff0c;需要…

使用表中的数组数据类型

在这篇文章中&#xff0c;我想跟进我以前关于Oracle集合数据类型的文章 &#xff0c;并且我将集中精力使用af&#xff1a;table组件中的oracle.jbo.domain.Array属性。 因此&#xff0c;在我的数据库中&#xff0c;我具有以下SQL类型&#xff1a; create or replace type var…

最伟大最不可思议最令人感动的父亲

转载于:https://www.cnblogs.com/chenou/archive/2007/10/23/935014.html

关于数据库名、实例名

最近因看到论坛有人问起这方面的东西&#xff0c;将自己的理解加上查阅相关资料整理如下&#xff0c;如果不全或不当的地方&#xff0c;望指正并补全它。 数据库名(DB_NAME)、实例名(Instance_name)、以及操作系统环境变量(ORACLE_SID) 在ORACLE7、8数据库中只有数据库名(db_…

linux 文件inode,linux文件系统-inode学习整理

linux文件系统-inode学习整理介绍linux文件系统可讲的模块有很多&#xff0c;包括文件系统整体架构、文件系统分类、虚拟文件系统以及文件系统存储结构等等&#xff0c;本文主要介绍的是文件系统的存储结构&#xff0c;也就是本文的重点-inode。文件存储结构首先从开天辟地开始…

操作方法:Maven的Spring Boot和Thymeleaf

Spring Boot是一款很棒的软件&#xff0c;可让您在几秒钟内引导Spring应用程序。 它确实有效。 尽可能少的配置即可上手。 而且仍然可以更改默认值。 让我们看看用Thymeleaf和Maven引导Spring MVC并在IntelliJ中使用它是多么容易。 Spring MVC Thymeleaf与Maven的基本设置 确…

csharp: 百度语音合成

public string API_id "3333"; //你的IDpublic string API_record null; public string API_record_format null; public string API_record_HZ null;public string API_key "geovindu"; //你的KEYpublic string API_secret_key "geovindu"…

20080408 - VS2003 中 Jscript 文件中文乱码问题

在 VS2003 中新建 Jscript 文件中使用中文时&#xff0c;如果和网页的编码不一致&#xff0c;有可能会出现中文乱码问题。 而 VS2003 的Web页面默认是用 UTF-8&#xff0c;这是多语的首选方案。 但 VS2003 产品的本地化工作可能做得不到位&#xff0c;在其中新建的 Jscript 文件…

一个简单的发布工具

自己写的一个简单工具&#xff0c;可以把做好的程序中的.cs,.sln,等代码文件排除掉&#xff0c;只剩下页面文件 是用.net 2.0做的程序文件 转载于:https://www.cnblogs.com/itants/archive/2007/10/24/935824.html

用于大型事件处理的Akka Java

我们正在设计一个大型的分布式事件驱动系统&#xff0c;用于跨事务数据库的实时数据复制。 来自源系统的数据&#xff08;消息&#xff09;在到达目的地之前经历了一系列转换和路由逻辑。 这些转换是多进程和多线程的操作&#xff0c;包括可以同时执行的较小的无状态步骤和任务…

pygame-KidsCanCode系列jumpy-part8-记录历史最高分

通常在多玩家的游戏中&#xff0c;每个玩家都会有自己的得分&#xff0c;最高分数会成为该游戏的最佳记录。这一篇&#xff0c;学习下如何记录最高得分&#xff1a;&#xff08;为了简化代码&#xff0c;本文采用文件方式&#xff0c;仅记录本机得分&#xff0c;明白原理后&…

linux下查看进度命令,在Linux系统中使用Coreutils Viewer显示命令运行进度

Coreutils Viewer(cv)是一个简单的程序&#xff0c;它可以用于显示任何核心组件命令(如&#xff1a;cp、mv、dd、tar、gzip、gunzip、cat、grep、fgrep、egrep、cut、sort、xz、exiting)的进度。它使用文件描述信息来确定一个命令的进度&#xff0c;比如cp命令。cv之美在于&…

每个Java开发人员都应该阅读的10本书

我已经阅读了自己的软件开发书籍&#xff0c;并且发现发现一本我想多次阅读的书籍非常罕见。 但是&#xff0c;有时我会发现一本书&#xff0c;每次阅读时都会教给我新的东西。 这篇博客文章是对这些稀有宝石的致敬。 现在&#xff0c;我毫不犹豫地向您介绍十本书&#xff0c…

存储过程生成流水号

1&#xff0c;首先在数据库中创建一个存放流水号的表 CREATE TABLE [dbo].[NumSeq] ([Cate] [varchar] (2) NOT NULL ,[DateNo] [varchar] (4) NOT NULL ,[Seq] [int] NULL ,[CrTime] [datetime] NOT NULL ) 上面的代码中&#xff0c;Cate 字段为流水号的头&#xff0c;可以…

tennylvHTML5实现屏幕手势解锁(转载)

来源:https://github.com/lvming6816077/H5lockhttp://threejs.org/examples/http://www.inf.usi.ch/phd/wettel/codecity-download.html (JSCity&#xff1a;把源码可视化成建筑物的 JS 库)http://www.alloyteam.com/2015/07/html5-shi-xian-ping-mu-shou-shi-jie-suo/ (Web前…

Linux中mysql的卸载和重装,linux mysql 卸载后重装

$sudo apt-get remove mysql-common清理残留数据:$sudo dpkg -l |grep ^rc|awk {print $2} |sudo xargs dpkg -P按照正常安装步骤安装注意:如果你想进行远程访问或控制&#xff0c;那么你要做两件事&#xff1a;其一&#xff1a;mysql>GRANT ALL PRIVILEGES ON xoops.* TO x…

NOIP模拟赛(by hzwer) T3 小奇回地球

【题目背景】 开学了&#xff0c;小奇在回地球的路上&#xff0c;遇到了一个棘手的问题。 【问题描述】 简单来说&#xff0c;它要从标号为 1 的星球到标号为 n 的星球&#xff0c;某一些星球之间有航线。 由于超时空隧道的存在&#xff0c;从一个星球到另一个星球时间可能会倒…