Java 8 introduced cool new features such as Lambdas and Streams. We'll take a look at what they are how to use them effectively. We'll also walkthrough an example of a lightweight Java 8 service running in AWS cloud, which can read and index tweets into an ElasticSearch cluster
TDD, BDD, ATDD are all methodologies that enable incremental design that is suitable for Agile environments. It seems that every day a new xDD methodology is born with the promise to be better than what came before. Should you use behaviour-driven tests or plain old unit tests? Which methodology is better? And how exactly would it benefit the development life cycle?
In this session, Dror will help to sort out the various methodologies – explaining where they came from, the tools they use, and discussing how and when to use each one. Here we will once and for all answer the question as to whether or not there’s one “DD” to rule them all.
The document contains 12 code snippets with multiple choice questions about Java concepts like threads, collections, serialization, patterns, and more. For each code snippet, 4 possible outputs are provided to choose from as the answer. The correct answers are also provided with brief explanations.
The document discusses avoiding new and delete in modern C++ code by using smart pointers and containers provided by the standard library and third-party libraries. It provides examples of managing memory with new/delete in C and early C++ compared to modern approaches using classes, constructors, destructors, and smart pointers. The document also discusses specific cases where new and delete may still be needed, such as with intrusive reference counting objects and some GUI frameworks. Overall, it promotes using make functions like make_unique, make_shared, and containers by default to simplify memory management in C++.
The document contains a list of 40 Java interview questions related to core Java, servlets, and JSP. The questions cover topics such as default array values, declaring and initializing arrays, Java keywords, if/else conditions, switch statements, loops, strings, wrappers, methods, threads, JDBC, servlet scopes, servlet lifecycle methods, differences between servlets and JSPs, implicit objects in JSP, and JSP directives.
This document provides 10 questions and answers related to the Sun Certified Programmer for the Java 2 Platform.SE 6.0 exam (310-065). The questions cover topics such as threads, exceptions, enums, inheritance, polymorphism and serialization. For each question there are multiple choice answers, with 1 or more answers being correctly marked.
Despite all of the recent interest, concurrency in standard C++ is still barely in its infancy. This talk uses the primitives supplied by C++14 to build a simple, reference, implementation of a task system. The goal is to learn to write software that doesn’t wait.
This document contains code examples demonstrating basic Java concepts like classes, objects, methods, constructors, static variables, and more. The examples show how to define Box classes with width, length and height attributes to calculate and print the volume. Later examples demonstrate method overloading, the use of this keyword, call by value vs reference, and default values of attributes. Constructors are used to initialize object attribute values.
This document provides an introduction to Test Driven Development (TDD) in Italian. It defines key TDD concepts like "test first" and automating tests. It then provides examples of using TDD to develop a parser for the "df" command output and features for an astrology horoscope application. The examples demonstrate the TDD process of writing a failing test, then code to pass the test, and refactoring. Rules for TDD like keeping tests passing and writing tests for all features are also outlined.
TDD, BDD, ATDD are all methodologies that enable incremental design that is suitable for Agile environments. It seems that every day a new xDD methodology is born with the promise to be better than what came before. Should you use behaviour-driven tests or plain old unit tests? Which methodology is better? And how exactly would it benefit the development life cycle?
In this session, Dror will help to sort out the various methodologies – explaining where they came from, the tools they use, and discussing how and when to use each one. Here we will once and for all answer the question as to whether or not there’s one “DD” to rule them all.
The document contains 12 code snippets with multiple choice questions about Java concepts like threads, collections, serialization, patterns, and more. For each code snippet, 4 possible outputs are provided to choose from as the answer. The correct answers are also provided with brief explanations.
The document discusses avoiding new and delete in modern C++ code by using smart pointers and containers provided by the standard library and third-party libraries. It provides examples of managing memory with new/delete in C and early C++ compared to modern approaches using classes, constructors, destructors, and smart pointers. The document also discusses specific cases where new and delete may still be needed, such as with intrusive reference counting objects and some GUI frameworks. Overall, it promotes using make functions like make_unique, make_shared, and containers by default to simplify memory management in C++.
The document contains a list of 40 Java interview questions related to core Java, servlets, and JSP. The questions cover topics such as default array values, declaring and initializing arrays, Java keywords, if/else conditions, switch statements, loops, strings, wrappers, methods, threads, JDBC, servlet scopes, servlet lifecycle methods, differences between servlets and JSPs, implicit objects in JSP, and JSP directives.
This document provides 10 questions and answers related to the Sun Certified Programmer for the Java 2 Platform.SE 6.0 exam (310-065). The questions cover topics such as threads, exceptions, enums, inheritance, polymorphism and serialization. For each question there are multiple choice answers, with 1 or more answers being correctly marked.
Despite all of the recent interest, concurrency in standard C++ is still barely in its infancy. This talk uses the primitives supplied by C++14 to build a simple, reference, implementation of a task system. The goal is to learn to write software that doesn’t wait.
This document contains code examples demonstrating basic Java concepts like classes, objects, methods, constructors, static variables, and more. The examples show how to define Box classes with width, length and height attributes to calculate and print the volume. Later examples demonstrate method overloading, the use of this keyword, call by value vs reference, and default values of attributes. Constructors are used to initialize object attribute values.
This document provides an introduction to Test Driven Development (TDD) in Italian. It defines key TDD concepts like "test first" and automating tests. It then provides examples of using TDD to develop a parser for the "df" command output and features for an astrology horoscope application. The examples demonstrate the TDD process of writing a failing test, then code to pass the test, and refactoring. Rules for TDD like keeping tests passing and writing tests for all features are also outlined.
KLEE is a symbolic virtual machine built on LLVM that generates automatic tests with high coverage by using symbolic execution and constraint solving. It is the successor to a similar tool called EXE and uses STP as its constraint solver. KLEE allows testing programs with symbolic inputs to achieve high code coverage and find bugs.
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
Assess your preparation with these Practice Test Questions with Explanation. Questions are Extracted from Highest Rated Course on Udemy which has helped a lot of students to pass the exam with good score.
500+ multiple choice questions with explanation to assess Oracle Certified Associate, Java SE 8 Programmer II preparation.
Highest Rated course on UDEMY
Read the students success stories at:
https://udayankhattry.com/ocp/
Enroll now to receive maximum discount on the course ie. for just $9.99 or ₹640.00, click the link below- https://www.udemy.com/java-ocp/?couponCode=UDAYANKHATTRY.COM
To avail maximum discount on all courses visit: www.udayankhattry.com
DeltaDoc is a technique that automatically generates natural language summaries of code changes from diffs. It works by symbolically executing the program to generate path predicates for statements, identifying statements that are added, removed, or have different predicates between versions, and applying summarization transformations to produce concise yet informative summaries. Evaluation found DeltaDoc summaries were on average more detailed than commit messages while being more concise, with about 89% able to cover the information in commit messages. DeltaDoc is designed to supplement or replace many existing commit messages by providing a structured, reliable summary of what changed in the code and how it impacts program behavior.
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
(better presented by @drpicox)
Slides of an introductory course for web programming focusing in basic Javascript and CSS concepts. It assumes knowledge of programming, Java or C#.
These slides contain an introduction to Symbolic execution and an introduction to KLEE.
I made this for a small demo/intro for my research group's meeting.
The document provides an overview of new features in C++20, including small language and library improvements. Some key points summarized:
1. Aggregate initialization allows initialization of aggregates using designated initializers (e.g. {.a = 3, .c = 7}) and direct initialization syntax (e.g. Widget w(1,2)).
2. Structured bindings allow capturing initialized variables from aggregates into auto variables (e.g. auto [a,b] = getWidget()).
3. Lambdas can be used in more contexts like static/thread_local variables and allow capturing initialized variables. Templates see expanded use of generic lambdas, non-type template parameters, and class
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
This document discusses pointcuts and static analysis in aspect-oriented programming. It provides an example of using aspects to ensure thread safety in Swing by wrapping method calls in invokeLater. It proposes representing pointcuts as relational queries over a program representation, and rewriting pointcuts as Datalog queries for static analysis. Representing programs and pointcuts relationally in this way enables precise static analysis of crosscutting concerns.
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...Flink Forward
This document discusses integrating deep learning models from Python frameworks like PyTorch and CNTK into Flink pipelines for real-time inference on streaming data. It presents ONNX as a standard format to export models, and explores options like using Java Embedded Python (JEP) to run models within Flink jobs or creating a microservice. Examples demonstrate named entity recognition and sentiment analysis on Twitter data streams using Flair models with JEP. Overall, the easiest approaches currently are using JEP to avoid converting models to ONNX and rewriting code, though native ONNX support in frameworks like Menoh, VESPA and Deeplearning4j may improve in the future.
The document contains a sample code with multiple questions and answers related to Java programming. The questions cover topics like arrays, exceptions, object-oriented programming concepts, and more. The provided code snippets have compilation errors, runtime exceptions or produce specific output. The correct answers are explained to assess the understanding of Java programming concepts.
Carol McDonald gave a presentation on the new features introduced in Java SE 5.0, including generics, autoboxing/unboxing, enhanced for loops, type-safe enumerations, varargs, and annotations. Generics allow type-safety when working with collections by specifying the collection element type. Autoboxing automatically converts between primitives and their corresponding wrapper types. The enhanced for loop simplifies iteration over collections. Type-safe enumerations provide an improved way of defining enum types. Varargs and annotations were also introduced to simplify coding patterns.
The document contains 15 multiple choice questions about inheritance in Java. Some key points covered include:
- Overriding vs overloading methods
- Access modifiers for methods in subclasses
- Calling superclass constructors and methods from subclasses
- Runtime polymorphism through inheritance
- Abstract methods and overriding rules
- Accessing subclass fields from superclass references
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
The document discusses several design patterns including decorator, composite, specification, and builder patterns. It provides examples of implementing a simple string decorator to add split and length methods. It also shows a composite pattern example using neurons and layers. The specification pattern is demonstrated for flexible filtering of product objects. Finally, fluent and Groovy-style builders are explored for constructing HTML elements in a cleaner way.
The document contains a quiz on Java fundamentals with 29 multiple choice questions covering topics like classes, objects, variables, data types, and methods. It tests understanding of concepts like inheritance, abstraction, polymorphism, and exceptions. The questions have a single correct answer option to select from to test comprehension of Java language rules and behavior.
In this chapter we will discuss exceptions in the object-oriented programming and in Java in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct.
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
OCJP Samples Questions: Exceptions and assertionsHari kiran G
The document contains sample questions and explanations for the OCP Java SE 8 exam related to exceptions and assertions. It includes multiple choice questions about exception handling, try-catch blocks, and assertion failures. The explanations provide details about which exceptions would be thrown and the output of code snippets.
The Ring programming language version 1.7 book - Part 92 of 196Mahmoud Samir Fayed
The document provides information about the Ring programming language including language keywords, functions, compiler errors, runtime errors, and environment errors.
It lists the 49 keywords used in Ring such as class, def, else, func, if, new, etc. It also lists 199 language functions organized alphabetically from add() to ring_state_setvar().
26 potential compiler errors are described that may occur during compilation such as errors in parameters, class names, missing brackets or parentheses. 15 runtime errors are also listed that could happen during execution like divide by zero, out of bounds array access, or calling undefined functions.
The document serves as a reference for the core components of the Ring language specification including the syntax rules
Interfaces in Java have evolved to include default methods, static methods, and functional interfaces in Java 8. Default methods allow interfaces to define implementations and provide backwards compatibility. Functional interfaces require only one abstract method, allowing lambda expressions to provide implementations. Traits encapsulate behaviors through default interface methods relying on a single abstract method.
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
HotSpot promises to do the "right" thing for us by identifying our hot code and compiling "just-in-time", but how does HotSpot make those decisions?
This presentation aims to detail how HotSpot makes those decisions and how it corrects its mistakes through a series of demos that you run yourself.
KLEE is a symbolic virtual machine built on LLVM that generates automatic tests with high coverage by using symbolic execution and constraint solving. It is the successor to a similar tool called EXE and uses STP as its constraint solver. KLEE allows testing programs with symbolic inputs to achieve high code coverage and find bugs.
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
Assess your preparation with these Practice Test Questions with Explanation. Questions are Extracted from Highest Rated Course on Udemy which has helped a lot of students to pass the exam with good score.
500+ multiple choice questions with explanation to assess Oracle Certified Associate, Java SE 8 Programmer II preparation.
Highest Rated course on UDEMY
Read the students success stories at:
https://udayankhattry.com/ocp/
Enroll now to receive maximum discount on the course ie. for just $9.99 or ₹640.00, click the link below- https://www.udemy.com/java-ocp/?couponCode=UDAYANKHATTRY.COM
To avail maximum discount on all courses visit: www.udayankhattry.com
DeltaDoc is a technique that automatically generates natural language summaries of code changes from diffs. It works by symbolically executing the program to generate path predicates for statements, identifying statements that are added, removed, or have different predicates between versions, and applying summarization transformations to produce concise yet informative summaries. Evaluation found DeltaDoc summaries were on average more detailed than commit messages while being more concise, with about 89% able to cover the information in commit messages. DeltaDoc is designed to supplement or replace many existing commit messages by providing a structured, reliable summary of what changed in the code and how it impacts program behavior.
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
(better presented by @drpicox)
Slides of an introductory course for web programming focusing in basic Javascript and CSS concepts. It assumes knowledge of programming, Java or C#.
These slides contain an introduction to Symbolic execution and an introduction to KLEE.
I made this for a small demo/intro for my research group's meeting.
The document provides an overview of new features in C++20, including small language and library improvements. Some key points summarized:
1. Aggregate initialization allows initialization of aggregates using designated initializers (e.g. {.a = 3, .c = 7}) and direct initialization syntax (e.g. Widget w(1,2)).
2. Structured bindings allow capturing initialized variables from aggregates into auto variables (e.g. auto [a,b] = getWidget()).
3. Lambdas can be used in more contexts like static/thread_local variables and allow capturing initialized variables. Templates see expanded use of generic lambdas, non-type template parameters, and class
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
This document discusses pointcuts and static analysis in aspect-oriented programming. It provides an example of using aspects to ensure thread safety in Swing by wrapping method calls in invokeLater. It proposes representing pointcuts as relational queries over a program representation, and rewriting pointcuts as Datalog queries for static analysis. Representing programs and pointcuts relationally in this way enables precise static analysis of crosscutting concerns.
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...Flink Forward
This document discusses integrating deep learning models from Python frameworks like PyTorch and CNTK into Flink pipelines for real-time inference on streaming data. It presents ONNX as a standard format to export models, and explores options like using Java Embedded Python (JEP) to run models within Flink jobs or creating a microservice. Examples demonstrate named entity recognition and sentiment analysis on Twitter data streams using Flair models with JEP. Overall, the easiest approaches currently are using JEP to avoid converting models to ONNX and rewriting code, though native ONNX support in frameworks like Menoh, VESPA and Deeplearning4j may improve in the future.
The document contains a sample code with multiple questions and answers related to Java programming. The questions cover topics like arrays, exceptions, object-oriented programming concepts, and more. The provided code snippets have compilation errors, runtime exceptions or produce specific output. The correct answers are explained to assess the understanding of Java programming concepts.
Carol McDonald gave a presentation on the new features introduced in Java SE 5.0, including generics, autoboxing/unboxing, enhanced for loops, type-safe enumerations, varargs, and annotations. Generics allow type-safety when working with collections by specifying the collection element type. Autoboxing automatically converts between primitives and their corresponding wrapper types. The enhanced for loop simplifies iteration over collections. Type-safe enumerations provide an improved way of defining enum types. Varargs and annotations were also introduced to simplify coding patterns.
The document contains 15 multiple choice questions about inheritance in Java. Some key points covered include:
- Overriding vs overloading methods
- Access modifiers for methods in subclasses
- Calling superclass constructors and methods from subclasses
- Runtime polymorphism through inheritance
- Abstract methods and overriding rules
- Accessing subclass fields from superclass references
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
The document discusses several design patterns including decorator, composite, specification, and builder patterns. It provides examples of implementing a simple string decorator to add split and length methods. It also shows a composite pattern example using neurons and layers. The specification pattern is demonstrated for flexible filtering of product objects. Finally, fluent and Groovy-style builders are explored for constructing HTML elements in a cleaner way.
The document contains a quiz on Java fundamentals with 29 multiple choice questions covering topics like classes, objects, variables, data types, and methods. It tests understanding of concepts like inheritance, abstraction, polymorphism, and exceptions. The questions have a single correct answer option to select from to test comprehension of Java language rules and behavior.
In this chapter we will discuss exceptions in the object-oriented programming and in Java in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct.
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
OCJP Samples Questions: Exceptions and assertionsHari kiran G
The document contains sample questions and explanations for the OCP Java SE 8 exam related to exceptions and assertions. It includes multiple choice questions about exception handling, try-catch blocks, and assertion failures. The explanations provide details about which exceptions would be thrown and the output of code snippets.
The Ring programming language version 1.7 book - Part 92 of 196Mahmoud Samir Fayed
The document provides information about the Ring programming language including language keywords, functions, compiler errors, runtime errors, and environment errors.
It lists the 49 keywords used in Ring such as class, def, else, func, if, new, etc. It also lists 199 language functions organized alphabetically from add() to ring_state_setvar().
26 potential compiler errors are described that may occur during compilation such as errors in parameters, class names, missing brackets or parentheses. 15 runtime errors are also listed that could happen during execution like divide by zero, out of bounds array access, or calling undefined functions.
The document serves as a reference for the core components of the Ring language specification including the syntax rules
Interfaces in Java have evolved to include default methods, static methods, and functional interfaces in Java 8. Default methods allow interfaces to define implementations and provide backwards compatibility. Functional interfaces require only one abstract method, allowing lambda expressions to provide implementations. Traits encapsulate behaviors through default interface methods relying on a single abstract method.
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
HotSpot promises to do the "right" thing for us by identifying our hot code and compiling "just-in-time", but how does HotSpot make those decisions?
This presentation aims to detail how HotSpot makes those decisions and how it corrects its mistakes through a series of demos that you run yourself.
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
This document provides an overview of Java 8 lambda features such as lambda syntax, interface enhancements like default methods, converting anonymous classes to lambdas, forEach and streams, method and constructor references, and functional interfaces. It also lists several sessions at a conference that will provide more in-depth coverage of these Java 8 lambda topics and includes links to documentation and additional resources.
This document discusses Fork/Join framework in Java 7. It explains that Fork/Join is designed to maximize usage of multiple processors by recursively splitting large tasks into smaller subtasks. It uses work-stealing algorithm where idle workers can steal tasks from busy workers' queues to balance load. An example of calculating Fibonacci numbers using Fork/Join is provided where the task is split recursively until the subproblem size is smaller than threshold, at which point it is computed directly.
The JVM JIT compiler and deoptimizer are triggered under certain conditions like method invocation counts, changes in program behavior, and hot spots. The JIT initially compiles code to generate fast machine instructions while the deoptimizer reverts back to interpreted execution if needed.
This document discusses new features in JDK 8 including lambda expressions, method references, default methods in interfaces, date and time API improvements, Nashorn JavaScript engine, parameter names in reflection, and annotation improvements. It also briefly mentions JEPs and upcoming features for JDK 9 such as modularity. The presenter provides code examples and explanations for many of the new JDK 8 language and API features.
The presentation introduces several new features in Java 8 including lambdas, default methods, streams API, and method references. Lambdas allow for anonymous functions and simplify implementing interfaces with single methods. Default methods allow interfaces to define implementations while maintaining backwards compatibility. The streams API provides a functional-style way to process collections through filtering, mapping, matching, and reducing operations. Method references allow referring to methods without anonymous classes.
- The document discusses best practices for micro-benchmarking in Java, including using frameworks like JMH that account for JVM warmup and avoid benchmark overhead.
- It explains common pitfalls like dead code elimination and loop unrolling that can incorrectly optimize away the code being measured.
- An example benchmark compares the performance of ArrayList and LinkedList iteration in different Java versions.
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
The document provides an overview of lambda expressions and functional interfaces in Java 8. It discusses key concepts like lambda functions, built-in functional interfaces like Predicate and Consumer, and how they can be used with streams. Examples are provided to demonstrate using lambdas with built-in interfaces like Predicate to filter a stream and Consumer to forEach over a stream. The document aims to help readers get hands-on experience coding with lambdas and streams in Java 8.
Carol McDonald gave a presentation on Java concurrency utilities introduced in J2SE 5.0. She discussed motivation for improved concurrency tools, common concurrency issues, and key utilities like Executor framework, locks, synchronizers, and concurrent collections. The utilities make concurrent programming easier and improve performance of multithreaded Java applications.
Here we are going to learn why is a good practice to use interfaces and how they are different from abstraction classes. Further more we are going to see how which one of them to use.
This document discusses object-oriented programming (OOP) principles and functional programming (FP) concepts. It covers SOLID principles like single responsibility, open/closed principles and dependency inversion. It also discusses design patterns like command and observer patterns and how they can be expressed functionally using higher-order functions. The document notes that popular programming languages have evolved from a multiparadigm approach in the 1980s to an object-oriented dominance period, and are now becoming increasingly multiparadigm again with integrated support for functional programming concepts.
Java 8 includes new functional features such as lambda expressions, method references, and streams. Lambda expressions allow for the creation of anonymous functions, and method references provide a way to refer to existing methods. Streams facilitate functional-style aggregate operations on data and support both sequential and parallel operations. Other features include default interface methods, closures, and static methods on interfaces.
The document discusses new features introduced in Java 8, including lambda expressions, functional interfaces, default and static methods in interfaces, and predefined functional interfaces like Predicate, Function, Consumer, and Supplier. It also covers stream API concepts like filtering, mapping, and processing streams using methods like collect(), count(), sorted(), min(), max(), forEach(), and toArray(). Stream API allows processing collections in a declarative way using lambda expressions and method references.
Learn about the basic fundamentals of java and important for the different company's interview. Topics like JRE, JDK, Java Keywords, Primitive DataTypes, Types of Variables, Logical, Shift and Bitwise Operator working, Command Line Argument, Handling Arrays, Array Copy, and different programs and output based programs.
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
While the new Streams API has been a great showcase for lambda methods, there are many other ways this new language feature can be used to make friendlier APIs and more expressive code. Lambdas can be used for a number of tasks which historically required significant boilerplate, type-unsafe constructs, or both. From new ways to express metedata, to emulating Groovy's null-safe navigation operator, we'll take a look at a myriad of ways, big and small, that you can use lambdas to improve APIs and streamline your code. We'll also look at some of the limitations of lambdas, and some techniques for overcoming them.
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Scala, Java 8 and Ruby become common. I will talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve the holy grail of OO, encapsulation.
The document provides an introduction to the Java programming language. It discusses Java's history and key editions. It also covers basic Java concepts like compiling and running a simple "Hello World" program, primitive data types, variables, operators, conditional statements like if/else, and iterative structures like the for loop. Examples are provided throughout to demonstrate syntax and output.
Similar to SoCal Code Camp 2015: An introduction to Java 8 (20)
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMHODECEDSIET
Time Division Multiplexing (TDM) is a method of transmitting multiple signals over a single communication channel by dividing the signal into many segments, each having a very short duration of time. These time slots are then allocated to different data streams, allowing multiple signals to share the same transmission medium efficiently. TDM is widely used in telecommunications and data communication systems.
### How TDM Works
1. **Time Slots Allocation**: The core principle of TDM is to assign distinct time slots to each signal. During each time slot, the respective signal is transmitted, and then the process repeats cyclically. For example, if there are four signals to be transmitted, the TDM cycle will divide time into four slots, each assigned to one signal.
2. **Synchronization**: Synchronization is crucial in TDM systems to ensure that the signals are correctly aligned with their respective time slots. Both the transmitter and receiver must be synchronized to avoid any overlap or loss of data. This synchronization is typically maintained by a clock signal that ensures time slots are accurately aligned.
3. **Frame Structure**: TDM data is organized into frames, where each frame consists of a set of time slots. Each frame is repeated at regular intervals, ensuring continuous transmission of data streams. The frame structure helps in managing the data streams and maintaining the synchronization between the transmitter and receiver.
4. **Multiplexer and Demultiplexer**: At the transmitting end, a multiplexer combines multiple input signals into a single composite signal by assigning each signal to a specific time slot. At the receiving end, a demultiplexer separates the composite signal back into individual signals based on their respective time slots.
### Types of TDM
1. **Synchronous TDM**: In synchronous TDM, time slots are pre-assigned to each signal, regardless of whether the signal has data to transmit or not. This can lead to inefficiencies if some time slots remain empty due to the absence of data.
2. **Asynchronous TDM (or Statistical TDM)**: Asynchronous TDM addresses the inefficiencies of synchronous TDM by allocating time slots dynamically based on the presence of data. Time slots are assigned only when there is data to transmit, which optimizes the use of the communication channel.
### Applications of TDM
- **Telecommunications**: TDM is extensively used in telecommunication systems, such as in T1 and E1 lines, where multiple telephone calls are transmitted over a single line by assigning each call to a specific time slot.
- **Digital Audio and Video Broadcasting**: TDM is used in broadcasting systems to transmit multiple audio or video streams over a single channel, ensuring efficient use of bandwidth.
- **Computer Networks**: TDM is used in network protocols and systems to manage the transmission of data from multiple sources over a single network medium.
### Advantages of TDM
- **Efficient Use of Bandwidth**: TDM all
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
14. Default Methods
14
public class Dog implements Bark {
// No overridden method
}
public interface Bark {
default String bark() {
return "Woof Woof!";
}
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark(); // Woof Woof!
}
26. Lambdas
26
Comparator<Student> c = new Comparator<Student>()
{
public int compare(Student a1, Student a2) {
return a1.getAge().compareTo(a2.getAge());
}
};
27. Lambdas
27
Comparator<Student> c = new Comparator<Student>()
{
public int compare(Student a1, Student a2) {
return a1.getAge().compareTo(a2.getAge());
}
};
Comparator<Student> c =
(Student a1, Student a2) ->
a1.getGrade().compareTo(a2.getGrade());
41. Streams
41
Stream is a sequence of elements from a
source that supports data processing
operations:
Fancy iterators that let you manipulate
collections of data in a declarative,
composable and transparently parallel way
53. CF
53
Future models an asynchronous computation and
provides a reference to its result that will be available
when the computation itself is completed
59. CF
59
Pattern 1: Async Sequencing
thenAccept*
Run a function when complete
thenApply*
Convert the result using a function when complete
60. CF
60
Pattern 2: Async Join
thenAcceptBoth*
Run a function when both futures are done
thenCombine*
Convert the result of 2 futures into a new thing
when both are done
61. CF
61
CF<String> user =
CF.supplyAsync(() -> "John");
CF<String> id =
CF.supplyAsync( () -> "1");
user
.thenCombineAsync(id, (u, i) -> u + i)
.thenAccept(System.out::println);
62. References
Java 8 in Action: https://www.manning.com/books/java-8-in-action
@Winterberg: http://winterbe.com/posts/2014/03/16/java-8-tutorial/
IntelliJ for Java Projects
62
64. Demo
64
Demo 1:
• Run code to periodically fetch tweets from Twitter
• Store the fetched tweets somewhere
Tech Stack used:
• AWS Lambda to create scheduled function
• AWS S3 to store fetched tweets
• Twitter Streaming Endpoint to fetch tweets
65. Demo
65
Demo 2:
• Index the stored tweets into an ElasticSearch cluster
• Explore and visualize patterns using Kibana Dashboards
Tech Stack used:
• AWS Lambda to create a function reacting to S3 events
• AWS ElasticSearch Service
• Kibana 4
http://www.oracle.com/us/technologies/java/duke-424174.html
Creator: Joe Palrang
Duke was designed to represent a "software agent" that performed tasks for the user.
Duke was the interactive host that enabled a new type of user interface that went beyond the buttons, mice, and pop-up menus of the desktop computing world
RedMonk Q3 2014 Programming Language Rankings
X axis: Popularity Rank on GitHub (by # of projects)
Y axis: Popularity Rank on StackOverflow (by # of tags)
GitHub and Stack Overflow are used here first because of their size and second because of their public exposure of the data necessary for the analysis
RedMonk Q3 2014 Programming Language Rankings
X axis: Popularity Rank on GitHub (by # of projects)
Y axis: Popularity Rank on StackOverflow (by # of tags)
GitHub and Stack Overflow are used here first because of their size and second because of their public exposure of the data necessary for the analysis
Language construct that groups related methods together into a contract. (HAS-A vs IS-A signaled by an abstract class)
Java 8 API introduces many new methods on existing interfaces, such as the sort method on the List
Java 8 API introduces many new methods on existing interfaces, such as the sort method on the List
How would maintainers of other libraries like Guava feel if they suddenly had to implement sort?
The main users of default methods are library designers.
default methods were introduced to evolve libraries such as the Java API in a compatible way
But even if you are an application developer this is important:
default methods can help structure your programs by providing a flexible mechanism for multiple inheritance of
behavior: a class can inherit default methods from several interface/classes
There are three kinds of compatibility when introducing a change to a Java program: binary, source, and behavioral compatibilities
Adding a method to an interface is binary compatible and behavioral compatible but NOT source compatible
Overlap: They both can contain abstract methods and methods with a body.
Difference 1: A class can extend only from one abstract class, but a class can implement multiple interfaces.
Difference 2: An abstract class can enforce a common state constants, members, method stubs and defined methods, whereas interfaces can only have constants methods stubs AND (now) default methods
Difference 3: Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
Meta Difference: Abstract class is for polling together behavior whereas interfaces act like contracts
What if the class implements two interfaces and both those interfaces define a default method with the same signature
1 Classes always win: A method declaration in the class or a superclass takes priority
over any default method declaration.
2 Otherwise, sub-interfaces win: the method with the same signature in the most
specific default-providing interface is selected. (If B extends A , B is more specific
than A ).
3 Finally, if the choice is still ambiguous, the class inheriting from multiple interfaces
has to explicitly select which default method implementation to use by
overriding it and calling the desired method explicitly:
new syntax X.super.m(…)
Where X is the superinterface whose method m you want to call.
1. Behavior parameterization is a software development pattern that lets you handle
frequent requirement changes.
2. It is the ability for a method to take multiple different behaviors as parameters and use them internally to accomplish different behaviors
3. In this sense its similar to Strategy Design pattern
4. Prior to Java 8, it could be encoded using anonymous classes
The Java 8 feature of passing code to methods (and also being able to return it and
incorporate it into data structures) also provides access to a whole range of additional
techniques that are commonly referred to as functional-style programming
Java 8 decided to allow methods to be values—to make it easier for
you to program. Moreover, the Java 8 feature of methods as values forms the basis of
various other Java 8 features (such as Stream s)
You could combine the grade and age into one method called 'filter':
But we'll still need a way to differentiate what attrobute to filter on
We could use flags but thats really ugly
What if the requirements mandate filtering based on not just a single attribute but a combination of attributes?
So far we have parameterized the filter method with values such
as a String, an Integer, or a boolean. But in this case what w eneed is a better way to tell your filter method
the selection criteria for students.
Creating a StudentPredicate interface and having multiple predicate objects implement that and then passing that interface as a second arg to filterStudents method can solve this in theory.
Cons: Unnecessary declaration of multiple objects/interfaces.
Anonymous classes could be used but they are bulky and distracting
We could use built-in method:
students.stream().filter(p -> p.age = 20).forEach(p -> System.out.println(p));
1. An interface is still a functional interface if it has many default methods as long as it specifies only one
abstract method.
2. The signature of the abstract method of the functional interface essentially describes
the signature of the lambda expression. We call this abstract method a function descriptor
Note that none of the new functional interfaces allow for a checked exception to be thrown.
You have two options if you need a lambda expression to throw an exception: define
your own functional interface that declares the checked exception, or wrap the lambda
with a try/catch block
Note that none of the new functional interfaces allow for a checked exception to be thrown.
You have two options if you need a lambda expression to throw an exception: define
your own functional interface that declares the checked exception, or wrap the lambda
with a try/catch block
The type of a lambda is deduced from the context in which the lambda is used.
The type expected for the lambda expression inside the context (for example, a method
parameter that it’s passed to or a local variable that it’s assigned to) is called the target
type
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
Lambdas and Closures:
A closure is an instance of a function that can reference
nonlocal variables of that function with no restrictions
Now Java 8 lambdas and anonymous classes do
something similar to closures: they can be passed as argument to methods and can
access variables outside their scope. But they have a restriction: they can’t modify
the content of local variables of a method in which the lambda is defined
Those variables have to be implicitly final. It helps to think that lambdas close over values rather
than variables
Allows us to reference constructors or methods without executing them.
Method references and Lambda are similar in that they both require a target type that consist of a compatible functional interface.
Java 8 enables you to pass references of methods or constructors via the :: keyword
4 types:
Static MR:
Arrays.sort(items, (a, b) -> Util.compareItems(a, b));
Arrays.sort(items, Util::compareItems);
Instance MR:
items.forEach((x) -> System.out.print(x));
items.forEach(System.out::print);
Reference to a method of arbitrary instance
items.forEach((x) -> { x.publish(); });
items.forEach(Item::publish);
Constructor reference
ConstructorReference cref = Item::new;
Item item = cref.constructor();
Streams are an update to the Java API that lets you manipulate collections of data in a
declarative way (you express a query rather than code an ad hoc implementation for
it)
1. Sequence of elements—Like a collection, a stream provides an interface to a
sequenced set of values of a specific element type. But Collections are about data; streams are about computations.
2. Source—Streams consume from a data-providing source such as collections,
arrays, or I/O resources.
3. Data processing operations—Streams support database-like operations and common
operations from functional programming languages to manipulate data,
such as filter, map, reduce, find, match, sort,
Much business logic entails database-like operations such as grouping, filtering, limiting a list of
entities by some constraint (for example, all old students)
We keep reimplementing these operations using iterators.
In contrast most databases let you specify such operations declaratively:
Express what you want done rather than how you want it done!
To gain performance you’d need to process it in parallel and leverage multicore architectures.
But writing parallel code is complicated in comparison to working with iterators.
In addition, it’s no fun to debug.
Declarative: Write code in a declarative way
Composable: Allows chaining to create data processing pipelines
Paralellizable: parallelXXX
In coarsest terms, the difference between collections and streams has to do with when
things are computed:
1. A collection is an in-memory data structure that holds all the values
the data structure currently has
2. A Stream is a conceptually fixed data structure (you can’t add or
remove elements from it) whose elements are computed on demand
3. You can see a stream as a set of values spread out in time.
In contrast, a collection is a set of values spread out in space
(here, computer memory), which all exist at a single point in time
Collections are about data; streams are about computations.
Netflix DVD vs Netflix Stream example
Sorted takes a Comparator:
Stream<T> sorted(Comparator<? super T> comparator)
static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor)
Stream operations have two important characteristics:
1. Pipelining: Many stream operations return a stream themselves, allowing operations
to be chained and form a larger pipeline allowing for laziness and short-circuiting.
2. Internal iteration: stream operations do the iteration behind the scenes for you.
Stream operations that can be connected are called intermediate operations, and operations
that close a stream are called terminal operations
Intermediate: filter, map, limit, skip, distinct, sorted
Terminal: forEach, collect, count, anyMatch, noneMatch, allMatch, findFirst, findAny, reduce/fold
What exactly happens when you call the method parallelStream() ?
How many threads are being used? What are the performance benefits?
Because operations such as filter (or sorted , map , and collect ) are available as
high-level building blocks that don’t depend on a specific threading model, their internal
implementation could be single-threaded or potentially maximize your multicore
architecture transparently
forEach: Consumes each element from a stream and applies a lambda to each of
them. The operation returns void.
Count: Returns the number of elements in a stream. The operation returns a long.
Collect: Reduces the stream to create a collection such as a List, a Map, or even
an Integer
<R> R collect(Supplier<R> supplier,
BiConsumer<R,? super T> accumulator,
BiConsumer<R,R> combiner)
Reduce:
T reduce(T identity,
BinaryOperator<T> accumulator)
// Reduce
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
reduce takes two arguments:
■ An initial value, here 0.
■ A BinaryOperator<T> to combine two elements and produce a new value; here
you use the lambda (a, b) -> a + b.
There’s also an overloaded variant of reduce that doesn’t take an initial value, but it
returns an Optional object
Optional<Integer> max = numbers.stream().reduce(Integer::max);
You can also get an empty stream using the empty method as follows:
Stream<String> emptyStream = Stream.empty();
Iterate:
Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
Generate:
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements etc
static <T> Stream<T> generate(Supplier<T> s)
https://jaxenter.com/java-performance-tutorial-how-fast-are-the-java-8-streams-118830.html
Concurrency is related to how an application handles multiple tasks it works on.
An application may process one task at at time (sequentially) or work on multiple tasks at the same time (concurrently).
Parallelism on the other hand, is related to how an application handles each individual task. An application may process the task serially from start to end, or split the task up into subtasks which can be completed in parallel.
[1] Concurrency:
Main goal is to perform several loosely related tasks on the same CPUs, keeping the
core as busy as possible to maximize the throughput of your application, what you
really want to achieve is to avoid blocking a thread and wasting its computational
resources while waiting
[2] Paralellism:
Split an operation into multiple suboperations and perform those
suboperations in parallel on different cores, CPUs, or even machines.
Specifically for Multicore processors we can take advantage via: FJ Framework + parallel streams
In recent years, two trends are obliging us to rethink the way we write software.
The first trend is related to the hardware on which we run our applications, and the second
trend concerns how applications are structured and particularly how they interact with each other
Since Java 1.5
Futures still dont allow you to write concise concurrent code.
CompletableFuture does.
For example, it’s difficult to express dependencies between
results of a Future ; declaratively it’s easy to say, “When the result of the long computation
is available, please send its result to another long computation, and when that’s
done, combine its result with the result from another query.” But implementing this
with the operations available in a Future is a different story
Combining two asynchronous computations in one—both when they're independent
and when the second depends on the result of the first
■ Waiting for the completion of all tasks performed by a set of Future s
■ Waiting for the completion of only the quickest task in a set of Future s (possibly
because they’re trying to calculate the same value in different ways) and retrieving
its result
■ Programmatically completing a Future (that is, by manually providing the
result of the asynchronous operation)
■ Reacting to a Future completion (that is, being notified when the completion
happens and then having the ability to perform a further action using the result
of the Future , instead of being blocked waiting for its result
The supplyAsync method accepts a Supplier as argument and returns a Completable-
Future that will be asynchronously completed with the value obtained by invoking
that Supplier .
This Supplier will be run by one of the Executor s in the ForkJoin-
Pool , but you can specify a different Executor by passing it as a second arg
Tenants for Reactive Programming
Avoid Blocking Thread (to optimize usage of all available cores)
Avoid changing threads (to optimize our use of cpu caches)
Avoid crippling failure (failure in a subsystem should be encapsulated and handled)
[1] and [2] are competing concerns
Parallel Streams and CompletableFutures both internally use the same common pool that by default has
a fixed number of threads equal to the one returned by:
Runtime.getRuntime().availableProcessors() .
Nevertheless, CompletableFutures have an advantage because, in contrast to what’s offered by the parallel Streams API , they allow you to
specify a different Executor to submit their tasks to.
This allows you to configure this Executor , and in particular to size its thread pool, in a way that better fits the
requirements of your application.
■ If you’re doing computation-heavy operations with no I/O, then the Stream interface
gives the simplest implementation and one likely to be the most efficient
(if all threads are compute-bound, then there’s no point in having more threads
than processor cores).
■ On the other hand, if your parallel units of work involve waiting for I/O (including
network connections), then CompletableFutures give more flexibility and the
ability to match the number of threads to the wait/computer, or W/C, ratio as
discussed previously. Another reason to avoid using parallel streams when I/O
waits are involved in the stream-processing pipeline is that the laziness of
streams can make it harder to reason about when the waits actually happen.
* = additional behavior happens on current thread (blocking)
*Async = additional behavior happens elsewhere
* = additional behavior happens on current thread (blocking)
*Async = additional behavior happens elsewhere