This document discusses various optimizations and improvements made to Java streams in recent versions. It provides examples of counting large streams, converting streams to arrays, collecting to lists, sorting, skipping elements, and using streams in parallel pipelines. It also covers characteristics of streams like SIZED, ORDERED, DISTINCT, and how operations like distinct(), skip(), and concat() perform in parallel scenarios. Overall it analyzes the performance of core stream operations and how their implementations have evolved.
Down to Stack Traces, up from Heap DumpsAndrei Pangin
Глубже стек-трейсов, шире хип-дампов
Stack trace и heap dump - не просто инструменты отладки; это потайные дверцы к самым недрам виртуальной Java машины. Доклад будет посвящён малоизвестным особенностям JDK, так или иначе связанным с обоходом хипа и стеками потоков.
Мы разберём:
- как снимать дампы в продакшне без побочных эффектов;
- как работают утилиты jmap и jstack изнутри, и в чём хитрость forced режима;
- почему все профилировщики врут, и как с этим бороться;
- познакомимся с новым Stack-Walking API в Java 9;
- научимся сканировать Heap средствами JVMTI;
- узнаем о недокументированных функциях Хотспота и других интересных штуках.
We aren't sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven't reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well.
JEEConf 2017 - Having fun with JavassistAnton Arhipov
Javassist makes Java bytecode manipulation simple. At ZeroTurnaround we use Javassist a lot to implement the integrations for our tools.
In this talk we will go through the examples of how Javassist can be applied to alter the applications behavior and do all kind of fun stuff with it.
Why is it interesting? Because while trying to do unusual things in Java, you learn much more about the language and the platform itself and learning about Javassist will actually make you a better Java developer!
No dark magic - Byte code engineering in the real worldtcurdt
ften byte code engineering is perceived as "black magic" and considered too low level. This session will not bore you with all the details of the JVM specification but provide you with a practical overview of how this byte code "swizzling" can be used in the real world instead. Several projects have sucessfully leveraged this technique to achieve some amazing things (e.g. AOP). This session will go through some of these examples and try to outline the differences between the two major libraries (BCEL and ASM). Maybe your next project can then benefit from some of this "magic".
Many projects use at least some of them - the Jakarta Commons libraries. Small reusable libraries simplifying the day-to-day work of thousands of java programmers. But over time the jakarta commons project has grown and the number of components makes it harder and harder to keep track. This session will try to give an overview of the components available and how the Jakarta Commons community is organized.
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
TestContainers is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.
Down to Stack Traces, up from Heap DumpsAndrei Pangin
Глубже стек-трейсов, шире хип-дампов
Stack trace и heap dump - не просто инструменты отладки; это потайные дверцы к самым недрам виртуальной Java машины. Доклад будет посвящён малоизвестным особенностям JDK, так или иначе связанным с обоходом хипа и стеками потоков.
Мы разберём:
- как снимать дампы в продакшне без побочных эффектов;
- как работают утилиты jmap и jstack изнутри, и в чём хитрость forced режима;
- почему все профилировщики врут, и как с этим бороться;
- познакомимся с новым Stack-Walking API в Java 9;
- научимся сканировать Heap средствами JVMTI;
- узнаем о недокументированных функциях Хотспота и других интересных штуках.
We aren't sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven't reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well.
JEEConf 2017 - Having fun with JavassistAnton Arhipov
Javassist makes Java bytecode manipulation simple. At ZeroTurnaround we use Javassist a lot to implement the integrations for our tools.
In this talk we will go through the examples of how Javassist can be applied to alter the applications behavior and do all kind of fun stuff with it.
Why is it interesting? Because while trying to do unusual things in Java, you learn much more about the language and the platform itself and learning about Javassist will actually make you a better Java developer!
No dark magic - Byte code engineering in the real worldtcurdt
ften byte code engineering is perceived as "black magic" and considered too low level. This session will not bore you with all the details of the JVM specification but provide you with a practical overview of how this byte code "swizzling" can be used in the real world instead. Several projects have sucessfully leveraged this technique to achieve some amazing things (e.g. AOP). This session will go through some of these examples and try to outline the differences between the two major libraries (BCEL and ASM). Maybe your next project can then benefit from some of this "magic".
Many projects use at least some of them - the Jakarta Commons libraries. Small reusable libraries simplifying the day-to-day work of thousands of java programmers. But over time the jakarta commons project has grown and the number of components makes it harder and harder to keep track. This session will try to give an overview of the components available and how the Jakarta Commons community is organized.
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
TestContainers is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
Introduction to Hadoop Map Reduce, Pig, Hive and Ambari technologies.
Workshop deck prepared and presented on September 5th 2015 by Radosław Stankiewicz.
During that the day participants had also the possibility to go through prepared tutorials and test their analysis on real cluster.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Железные счётчики на страже производительностиSergey Kuksenko
Нередко при анализе производительности приложений приходится много копать. Но просто копать недостаточно, нужно еще разгребать накопанное. Железный век настал более 3000 лет назад, и было бы удивительно, если бы за это время человечество не создало кучу разнообразных железных приспособлений для копания и разгребания.
Данный доклад рассказывает, что же такое «Hardware Performance Counters», где их найти и как их можно использовать для анализа производительности.
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
Introduction to Hadoop Map Reduce, Pig, Hive and Ambari technologies.
Workshop deck prepared and presented on September 5th 2015 by Radosław Stankiewicz.
During that the day participants had also the possibility to go through prepared tutorials and test their analysis on real cluster.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Железные счётчики на страже производительностиSergey Kuksenko
Нередко при анализе производительности приложений приходится много копать. Но просто копать недостаточно, нужно еще разгребать накопанное. Железный век настал более 3000 лет назад, и было бы удивительно, если бы за это время человечество не создало кучу разнообразных железных приспособлений для копания и разгребания.
Данный доклад рассказывает, что же такое «Hardware Performance Counters», где их найти и как их можно использовать для анализа производительности.
JDK8 is bringing lambdas into the Java world. But without significant Java SE 8 libraries extensions lambdas would be only a toy. The centerpiece of the new libraries is the Streams API (formerly ‘Collections bulk operations’). This session presents the Streams API and examples how to get the best performance and scalability using the library.
Nowadays, CPU microarchitecture is concealed from developers by compilers, VMs, etc.
Do Java developers need to know microarchitecture details of modern processors?
Or, does it like to learn quantum mechanics for cooking?
Are Java developers safe from leaking low-level microarchitecture details into high level application performance behaviour?
We will try to answer these questions by analyzing several Java examples.
Keynote that I gave at JavaLand 2015, in Brühl, Germany. Talks about 20 years of Java and JVM technology from my subjective perspective. "What have I been doing with my life for the last 20 years".
Nowadays, CPU microarchitecture is concealed from developers by compilers, VMs, etc. Do Java developers need to know microarchitecture details of modern processors? Or, does it like to learn quantum mechanics for cooking? Are Java developers safe from leaking low-level microarchitecture details into high level application performance behaviour? We will try to answer these questions by analyzing several Java example.
Java 8 Puzzlers as it was presented at Codemash 2017Baruch Sadogursky
We aren’t sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven’t reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well. Baruch and Viktor will show you some surprising, bizarre, and inconceivable parts of Java 8 and make sure that you won’t be (too) surprised when it hits you in production. As with any other puzzlers talk, there will be two speakers, lots of puzzling questions, answers by the audience, T-shirts flying around, and a lot of fun, all for one purpose—to help you better understand Java 8.
Java Performance: Speedup your application with hardware countersSergey Kuksenko
A modern CPU looks under the cover to understand what performance. What about hardware for Java application performance? Let's understand Performance Monitoring Unit works, Hardware Counters & using them to speeding up Java apps.
This is a 3 part series on Java8 Features. Drop me an email for a discussion - singh.marut@gmail.com
https://github.com/singhmarut/java8training
Videos available at my youtube channel https://www.youtube.com/channel/UCBM4yHwfjQ_syW6Lz8kYpmA
The new Java 8 stream library is the most exciting addition to come to Java in a long time. It allows entire algorithms to be expressed in one line, parallelism to be obtained on-demand, and plumbing code to be flushed down the drain. This presentation will show you how to think in streams, effective parallelization, plus advanced concepts like mutable reduction and declarative collection. Write better code with streams. This presentation will show you how.
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
Rx и Kotlin стали самыми модными трендами Android разработки в последнее время. Мы выпустили два приложения с архитектурой, построенной вокруг Rx, где нет ни одной строки на Java. Насколько удобно работать с этими инструментами? В своём докладе я расскажу, с какими трудностями мы столкнулись, как их победили, а также продемонстрирую несколько крутых и несложных подходов к разработке на этом стеке.
Apache Spark for Library Developers with William Benton and Erik ErlandsonDatabricks
As a developer, data engineer, or data scientist, you’ve seen how Apache Spark is expressive enough to let you solve problems elegantly and efficient enough to let you scale out to handle more data. However, if you’re solving the same problems again and again, you probably want to capture and distribute your solutions so that you can focus on new problems and so other people can reuse and remix them: you want to develop a library that extends Spark.
You faced a learning curve when you first started using Spark, and you’ll face a different learning curve as you start to develop reusable abstractions atop Spark. In this talk, two experienced Spark library developers will give you the background and context you’ll need to turn your code into a library that you can share with the world. We’ll cover: Issues to consider when developing parallel algorithms with Spark, Designing generic, robust functions that operate on data frames and datasets, Extending data frames with user-defined functions (UDFs) and user-defined aggregates (UDAFs), Best practices around caching and broadcasting, and why these are especially important for library developers, Integrating with ML pipelines, Exposing key functionality in both Python and Scala, and How to test, build, and publish your library for the community.
We’ll back up our advice with concrete examples from real packages built atop Spark. You’ll leave this talk informed and inspired to take your Spark proficiency to the next level and develop and publish an awesome library of your own.
A practical guide to using RxJava on Android. Tips for improving your app architecture with reactive programming. What are the advantages and disadvantages of using RxJava over standard architecture? And how to connect with other popular Android libraries?
Presented at Droidcon Greece 2016.
This talk is a look into some of the surprising performance cases in Java -- with the goal of illustrating a few simple truths about the nature of compilers.
Apache Hive is a data warehouse software project built on top of Apache Hadoop for providing data summarization, query, and analysis.
For More Information visit us:
http://www.kalyanhadooptraining.com
Similar to JPoint 2016 - Валеев Тагир - Странности Stream API (20)
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Enhancing Performance with Globus and the Science DMZGlobus
ESnet has led the way in helping national facilities—and many other institutions in the research community—configure Science DMZs and troubleshoot network issues to maximize data transfer performance. In this talk we will present a summary of approaches and tips for getting the most out of your network infrastructure using Globus Connect Server.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
2. Что это за чувак на сцене?
https://github.com/amaembo/streamex
2
3. Что это за чувак на сцене?
• JDK-8072727 Add variation of Stream.iterate() that's finite
• JDK-8136686 Collectors.counting can use Collectors.summingLong to reduce boxing
• JDK-8141630 Specification of Collections.synchronized* need to state traversal constraints
• JDK-8145007 Pattern splitAsStream is not late binding as required by the specification
• JDK-8146218 Add LocalDate.datesUntil method producing Stream<LocalDate>
• JDK-8147505 BaseStream.onClose() should not allow registering new handlers after stream is
consumed
• JDK-8148115 Stream.findFirst for unordered source optimization
• JDK-8148250 Stream.limit() parallel tasks with ordered non-SUBSIZED source should short-circuit
• JDK-8148838 Stream.flatMap(...).spliterator() cannot properly split after tryAdvance()
• JDK-8148748 ArrayList.subList().spliterator() is not late-binding
• JDK-8151123 Collectors.summingDouble/averagingDouble unnecessarily call mapper twice
3
12. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.stream.SpinedBuffer$OfInt.newArray
at java.util.stream.SpinedBuffer$OfInt.newArray
at java.util.stream.SpinedBuffer$OfPrimitive.asPrimitiveArray
at java.util.stream.Nodes$IntSpinedNodeBuilder.asPrimitiveArray
at java.util.stream.Nodes$IntSpinedNodeBuilder.asPrimitiveArray
at java.util.stream.IntPipeline.toArray
at ru.javapoint.streamsamples.ToArray.main
12
19. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.stream.SpinedBuffer$OfInt.newArray
at java.util.stream.SpinedBuffer$OfInt.newArray
at java.util.stream.SpinedBuffer$OfPrimitive.asPrimitiveArray
at java.util.stream.Nodes$IntSpinedNodeBuilder.asPrimitiveArray
at java.util.stream.Nodes$IntSpinedNodeBuilder.asPrimitiveArray
at java.util.stream.IntPipeline.toArray
at ru.javapoint.streamsamples.ToArraySkip.main
19
25. parallel().skip()
API Note:
While skip() is generally a cheap operation on sequential
stream pipelines, it can be quite expensive on ordered
parallel pipelines, especially for large values of n,
since skip(n) is constrained to skip not just any n elements, but
the first n elements in the encounter order.
25
32. parallel().distinct()
API Note:
Preserving stability for distinct() in parallel pipelines is
relatively expensive (requires that the operation act as a full
barrier, with substantial buffering overhead), and stability is
often not needed. Using an unordered stream source (such as
generate(Supplier)) or removing the ordering constraint with
BaseStream.unordered() may result in significantly more
efficient execution for distinct() in parallel pipelines, if the
semantics of your situation permit.
32
40. concat() и parallel()
Integer[] aIntegers = { 101, 102, ..., 200 };
Integer[] bIntegers = { 201, 202, ..., 300 };
Stream<Integer> a = Arrays.stream(aIntegers);
Stream<Integer> b = Arrays.stream(bIntegers);
List<String> list = Stream.concat(a, b)
.map(num -> String.valueOf(num).replaceAll("((((.*)*)*)*)*!", ""))
.collect(Collectors.toList());
868.9 ± 10.6 ms
40
41. concat() и parallel()
Integer[] aIntegers = { 101, 102, ..., 200 };
Integer[] bIntegers = { 201, 202, ..., 300 };
Stream<Integer> a = Arrays.stream(aIntegers);
Stream<Integer> b = Arrays.stream(bIntegers);
List<String> list = Stream.concat(a, b)
.parallel()
.map(num -> String.valueOf(num).replaceAll("((((.*)*)*)*)*!", ""))
.collect(Collectors.toList());
227.9 ± 3.5 ms (3.8×)
41
42. concat() и parallel()
Stream<Integer> a = Arrays.stream(aIntegers);
Stream<Integer> b = Arrays.stream(bIntegers);
List<String> list = Stream.concat(a, b)
.parallel() 227.9
.map(num -> String.valueOf(num).replaceAll(...)) ± 3.5 ms
.collect(Collectors.toList()); (3.8×)
Stream<Integer> a = Arrays.stream(aInts).boxed();
Stream<Integer> b = Arrays.stream(bInts).boxed();
List<String> list = Stream.concat(a, b)
.parallel() ?
.map(num -> String.valueOf(num).replaceAll(...))
.collect(Collectors.toList());
42
43. concat() и parallel()
Stream<Integer> a = Arrays.stream(aIntegers);
Stream<Integer> b = Arrays.stream(bIntegers);
List<String> list = Stream.concat(a, b)
.parallel() 227.9
.map(num -> String.valueOf(num).replaceAll(...)) ± 3.5 ms
.collect(Collectors.toList()); (3.8×)
Stream<Integer> a = Arrays.stream(aInts).boxed();
Stream<Integer> b = Arrays.stream(bInts).boxed();
List<String> list = Stream.concat(a, b)
.parallel() 437.8
.map(num -> String.valueOf(num).replaceAll(...)) ± 5.2 ms
.collect(Collectors.toList()); (1.98×)
43
44. concat()
1. Пусть A = aStream.spliterator(), B = bStream.spliterator()
2. Создать новый spliterator из этих двух:
• tryAdvance: вызывать A.tryAdvance(),
а если там кончилось, то B.tryAdvance().
• forEachRemaining: вызвать A.forEachRemaining(),
затем B.forEachRemaining().
• trySplit: разделить назад на A и B.
3. Создать новый stream по новому сплитератору.
4. Повесить на onClose вызов aStream.close() и
bStream.close()
44
45. Stream.spliterator()
1. Нет промежуточных операций? Вернём исходный сплитератор.
2. Есть промежуточные операции? Создадим новый WrappingSpliterator:
• forEachRemaining(): ≈ Stream.forEach()
• tryAdvance(): вызвать tryAdvance у источника и собрать в буфер,
что накопилось, а потом идти по буферу
• trySplit(): если исходный стрим параллельный, вызвать trySplit() у
источника и обернуть результат в такой же WrappingSpliterator
45
46. concat() и parallel()
Stream<Integer> a = Arrays.stream(aIntegers);
Stream<Integer> b = Arrays.stream(bIntegers);
List<String> list = Stream.concat(a, b)
.parallel() 227.9
.map(num -> String.valueOf(num).replaceAll(...)) ± 3.5 ms
.collect(Collectors.toList()); (3.8×)
Stream<Integer> a = Arrays.stream(aInts).boxed();
Stream<Integer> b = Arrays.stream(bInts).boxed();
List<String> list = Stream.concat(a, b)
.parallel() 437.8
.map(num -> String.valueOf(num).replaceAll(...)) ± 5.2 ms
.collect(Collectors.toList()); (1.98×)
46
47. concat() и parallel()
Stream<Integer> a = Arrays.stream(aInts).boxed().parallel();
Stream<Integer> b = Arrays.stream(bInts).boxed().parallel();
List<String> list = Stream.concat(a, b)
.map(num -> String.valueOf(num).replaceAll(...))
.collect(Collectors.toList());
222.1 ± 2.3 ms (3.9×)
47
48. concat() и ordering
List<Integer> a = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> b = Arrays.asList();
Stream.concat(a.parallelStream(), b.parallelStream())
.filter(x -> x % 2 == 0)
.limit(3)
.forEachOrdered(System.out::println);
>> 2
>> 4
>> 6
48
49. concat() и ordering
List<Integer> a = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> b = Collections.emptyList();
Stream.concat(a.parallelStream(), b.parallelStream())
.filter(x -> x % 2 == 0)
.limit(3)
.forEachOrdered(System.out::println);
>> 2
>> 6
>> 10
49
50. flatMap()
Stream<Integer> a = ...;
Stream<Integer> b = ...;
Stream<Integer> c = ...;
Stream<Integer> d = ...;
Stream<Integer> res = Stream.concat(
Stream.concat(Stream.concat(a, b), c), d);
Stream<Integer> res = Stream.of(a, b, c, d)
.flatMap(Function.identity());
50
51. concat() или flatMap()?
Stream<Integer> a = Arrays.stream(aInts).boxed().parallel();
Stream<Integer> b = Arrays.stream(bInts).boxed().parallel();
List<String> list = Stream.of(a, b)
.flatMap(Function.identity())
.parallel()
.map(num -> String.valueOf(num).replaceAll(...))
.collect(Collectors.toList()); // 444.8 ± 7.3 ms (1.95x)
51
55. flatMap() и tryAdvance()
Stream<Integer> s = IntStream.of(1_000_000_000)
.flatMap(x -> IntStream.range(0, x)).boxed();
s.spliterator().tryAdvance(System.out::println);
55
56. java.lang.OutOfMemoryError: Java heap space
at java.util.stream.SpinedBuffer.ensureCapacity
at java.util.stream.SpinedBuffer.increaseCapacity
at java.util.stream.SpinedBuffer.accept
at java.util.stream.IntPipeline$4$1.accept
at java.util.stream.IntPipeline$7$1.lambda$accept$198
at java.util.stream.IntPipeline$7$1$$Lambda$7/1831932724.accept
at java.util.stream.Streams$RangeIntSpliterator.forEachRemaining
at java.util.stream.IntPipeline$Head.forEach
at java.util.stream.IntPipeline$7$1.accept
at java.util.stream.Streams$IntStreamBuilderImpl.tryAdvance
at java.util.Spliterator$OfInt.tryAdvance
...
at java.util.stream.StreamSpliterators$WrappingSpliterator.tryAdvance
at ru.javapoint.streamsamples.FlatMapTryAdvance.main
56
57. flatMap() и tryAdvance()
Stream<Integer> s = IntStream.of(1_000_000_000)
.flatMap(x -> IntStream.range(0, x)).boxed();
s.spliterator().tryAdvance(System.out::println);
57
58. flatMap() и concat()
IntStream s = IntStream.of(1_000_000_000)
.flatMap(x -> IntStream.range(0, x));
s.sum();
s.findFirst(); // non short-circuit
IntStream.concat(s, IntStream.of(1)).sum();
IntStream.concat(s, IntStream.of(1)).findFirst();
58
59. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.stream.SpinedBuffer$OfInt.newArray
at java.util.stream.SpinedBuffer$OfInt.newArray
at java.util.stream.SpinedBuffer$OfPrimitive.ensureCapacity
at java.util.stream.SpinedBuffer$OfPrimitive.increaseCapacity
at java.util.stream.SpinedBuffer$OfPrimitive.preAccept
at java.util.stream.SpinedBuffer$OfInt.accept
...
at java.util.stream.Streams$ConcatSpliterator$OfInt.tryAdvance
at java.util.stream.IntPipeline.forEachWithCancel
at java.util.stream.AbstractPipeline.copyIntoWithCancel
at java.util.stream.AbstractPipeline.copyInto
at java.util.stream.AbstractPipeline.wrapAndCopyInto
at java.util.stream.FindOps$FindOp.evaluateSequential
at java.util.stream.AbstractPipeline.evaluate
at java.util.stream.IntPipeline.findFirst
at ru.javapoint.streamsamples.ConcatFlat.main 59
60. flatMap() vs concat()
concat() flatMap()
Сохраняет SIZED
Short-circuiting
Memory-friendly tryAdvance()
Полноценный параллелизм
Всегда сохраняет порядок
Многократная конкатенация
±
60
61. Всё же concat()?
Object[][] data = new Object[20000][4000];
Object[] flat = Arrays.stream(data)
.flatMap(Arrays::stream).toArray();
>> java.lang.OutOfMemoryError
61
62. Всё же concat()?
Object[][] data = new Object[20000][4000];
Object[] flat = Arrays.stream(data)
.flatMap(Arrays::stream).toArray();
>> java.lang.OutOfMemoryError
Stream<Object> s = Arrays.stream(data)
.map(Arrays::stream).reduce(Stream::concat)
.orElse(Stream.empty());
Object[] flat = s.toArray();
62
63. Exception in thread "main" java.lang.StackOverflowError
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining
... 63
69. for vs forEach()
for forEach()
Появился Java 1.5 Java 1.8
Нормальная отладка
Короткие стектрейсы
Checked exceptions
Изменяемые переменные
Досрочный выход по break
Параллелизм (всё равно не нужен) 69
73. iterator()
IntStream s = IntStream.of(1_000_000_000)
.flatMap(x -> IntStream.range(0, x));
for(int i : (Iterable<Integer>)s::iterator) {
System.out.println(i);
}
73
74. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at j.u.s.SpinedBuffer$OfInt.newArray
at j.u.s.SpinedBuffer$OfInt.newArray
at j.u.s.SpinedBuffer$OfPrimitive.ensureCapacity
at j.u.s.SpinedBuffer$OfPrimitive.increaseCapacity
at j.u.s.SpinedBuffer$OfPrimitive.preAccept
at j.u.s.SpinedBuffer$OfInt.accept
at j.u.s.IntPipeline$7$1.lambda$accept$198
...
at j.u.s.StreamSpliterators$AbstractWrappingSpliterator.fillBuffer
at j.u.s.StreamSpliterators$AbstractWrappingSpliterator.doAdvance
at j.u.s.StreamSpliterators$IntWrappingSpliterator.tryAdvance
at j.u.Spliterators$2Adapter.hasNext
at ru.javapoint.streamsamples.IterableWorkaround.main
74