Java_advanced Flashcards

1
Q

What does this course cover?

A

Topics advanced Java developers use a daily basis.

Designed as a step by step guide and reference.

Each section builds on top of itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the requirements?

A

Should know the basics of OOP in Java!

Start from part 1 or part 2 of the series!

Or you’ll find the topics difficult to understand!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is covered in the exceptions section?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the root cause of many problems in Java programs?

A

NullPointerException

A class declared in java.lang package

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is an exception?

A

An object that contains information about an error

Several exception classes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What should a good Java developer anticipate?

A

Exceptions and handle them!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the three types of exceptions in Java?

A

Checked Exceptions :

Exceptions we as developers should anticipate and handle

Exceptions forced to handle by Java compiler

Checked at compile time by java compiler (red underline)

Ex. Handle edge cases vs. runtime terminating program

Unchecked (runtime exceptions) :

not checked during compile time by Java Compiler

due to programming errors

Ex. NullPointerException due to trying to pass a null value as an object reference

Error

error external to our application

Ex. memory error, stack overflow error

Solution?

identify source like infinite recursion or problem with JVM itself

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are checked exceptions?

A

Exceptions we should anticipate and recover from vs. runtime terminating program​

Exceptions we as developers should anticipate and handle

Exceptions forced to handle by Java compiler

Checked at compile time by java compiler (red underline)

Ex. Java compiler knows constructor will throw an exception if file is not present, must handle this edge case

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are unchecked exceptions (run time exceptions)?

A

Programming errors

not checked during compile time by Java Compiler

NullPointerException - due to trying to pass a null value as an object reference

ArithmeticException - attempt to divide by zero

IllegalArgumentException - argument passed to method not accepted

IndexOutOfBoundsException - access an array, list, string invalid index

IllegalStateExceptions - call a method, object not in correct state

Solve?

Automated Testing, lots of testing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are errors?

A

errors resulting from problems external to our application

Ex.

StackOverFlowError

OutOfMemoryError

Source?

Infinite looping, JVM issues

Solve?

Let application crash, identify error source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the stack trace?

A

Shows the methods that have been called (in reverse order) that resulted in an exception

Why?

Useful in solving problems & identifiying sources of exceptions, errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What can throw an exception?

A

A method can throw an exception

or cause of chain of exceptions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the exceptions hierarchy?

A

Classes that represent different types of exceptions

Top of Hierarchy:

Throwable Class - defines common characteristics for all exceptions and errors like an error message and stack trace

Next Level:

Exception Class - parent class for all checked and unchecked errors, if not RunTimeException it’s a checked error

Error Class - + all children classes represent errors external to our application errors

Below Exception Class:

RunTimeException Class - unchecked exceptions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What will Java run time compiler do when a method throws an exception?

A

Look for an exception handler

If the method doesn’t have a method to handle the exception, will look at other methods

if none are present, Java Run Time will terminate the program and deliver exception message

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

E What is the proper way to handled checked exceptions?

A

Catch exceptions using try-catch blocks!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can we use IntelliJ to generate a catch for a checked error?

A

Option + enter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do we catch multiple types of exceptions?

A

Multiple catch blocks

each catch block targets a specific exception

if method throws an exception

catch block will catch exception and handle it

Sometimes order matters!

Why?

A parent object might get called first, resulting in absence of polymorphism (child object not getting called)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How can we refactor these exceptions?

A

Combine the two exceptions using a vertical bar

block will catch exceptions of type IOException or ParseException and handle them the same

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the finally block?

A

Comes after catch statement

always gets excuted (whether there is an exception or not)

allows us to release external resouces

Release:

File Handles - reader.close ( );

Network connections

Database connections

Why?

If we don’t release these ext. resources other methods may not be able to access them!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is a better way to release resources (than finally block)?

A

use try-with-resources statement

a try statement with one or more resources

We don’t need to explicitly close resources

Syntax?

initialize external resources after try statement before block using ( )

Why?

JavaCompiler will automatically create finally block (at runtime, under the hood, close resources)

But?

Objects initialized in try-with-resource statement must implement the auto-closeable interface

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How can we throw an exception?

A

Use the throw keyword!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is defensive programming?

A

validating an argument, throwing an exception if outside of valid range

Why?

stopping code from running is better than letting a serious problem occur later in our application

When?

if an error could occur that causes problems with the rest of our code

Do?

Throw an exception to prevent rest of code from running if an error occurs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

When is it better to use defensive programming?

A
  1. When building a library for others to use
  2. When recieving data from external sources outside of application

Why?

Defensive programming makes your code verbose

If building an application, methods should trust each other, don’t need to pollute your code with tons of data validation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do we specify that our method may throw an exception so that the receiving class can handle this exception?

A

Add the throws keyword after parameter declaration

details represent API of this method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
**Why** and **how** do we **re-throw** an **exception**?
**Why?** Our **application handles the exceptio**n BUT **we want to log it somewhere else** so we can handle it and re-throw it **How?** add ***throw*** keyword in catch block add ***throws*** to the **method signature** after parameter declaration **IntelliJ** can also shortcut do this!
26
**What** are **custom exceptions**?
**Java provides** a lot of **generic exceptions** class BUT **sometimes we want to create custom exceptions** **Why?** **Sometimes** we need to create **exceptions specific to our application domain** **When?** **Creating libraries or frameworks** that have custom exceptions to **help users and other developers** understand intent and **actual problem**
27
**What** is the **naming convention** for **Exceptions Classes**?
***Exceptions* -suffix** to **name our Exceptions Classes** Ex. InsufficientFunds**Exception**
28
**How** do we **create** a **custom exception**?
**Naming** -Exceptions for **suffix** add ***extends*** + **parent class name**
29
**What** is **chainining exceptons**?
**Wrapping a more specific exception** **object** inside **a** **general exception object** **Why?** Find out **specific details** on **what caused** the **general exception** Ex. **AccountException** caused by **InsufficientFundsException** **How?** Create **Parent Exception Class** pass **detailed** **exception object** in the constructor of this **wrapper object** **When?** **Used** in **building libraries** and **frameworks** **Used** in **building large,** **enterprise applications**
30
**What** is a **simpler way** to **chain exceptions**?
31
**What** are **generics**?
**One** of the **most important topics** in **Java** **Why?** Many **collection classes** are i**mplemented** using **Generics**
32
**What** problem do **generics solve**?
**Duplicate code** **Why?** **Having** to create **data structures** for **each data type** (**integer, objects, Strings**) is tedious!! Causes **lots of duplicate code**!! **Solution?** **Generic**s - They offer **polymorphism to collections**
33
**Why** is using the base **Object class** a **problematic implementation**?
**To store values in return variable** have to **explicitly cast result** to **specific data type** **if** accidently **try to cast data to the wrong type**, **get a runtime exception (ClassCastException)**
34
**How** do we **specify generic type**?
After **class name** add **T for type or template** **E for element (collections)** **Method Return Type = T** **Method Parameter Type = T**
35
**What** are the **benefits of generics**?
1. **Compile Time, Type Safety** - provides compile time errors that ensure all objects are of the specified data type 2. **Cleaner code** - **don't have to explicitly** cast **return types**
36
**How** do we **use primitives** with **generic classes**?
Cannot use **primititve type directly** **Must wrapper classes** around **primitive types** int -\> **Integer** boolean -\> **Boolean** float -\> **Float**
37
What is **boxing**?
Java **run time compiler** will **take a primitive value** and **wrap it** in a **wrapper class (reference type)**
38
**What** is **unboxing**?
**Java compiler** extracts **value stored** in **Integer reference type** **can be then** stored in a **primitive type variable**
39
**How** do we implement **type constraints** in a **generic class**?
add ***extend***s keyword + **type** Ex. **extends** Number\> **Can only** use generic with **Number class** or **any derivative** **classes** (Integer, Float, etc.)
40
**How** can we restrict our **generic class** using **interfaces (bounded type parameter)**?
Create a **bounded type parameter**: **add** ***extends*** + **interfaces** \<**T** **extends** **Comparable & Cloneable\>** only allow types that implement interface Ex. **Generic list** can only **store objects** that are **comparable and clonable**
41
**What** is a **bounded type parameter**?
**A generic** that **only accepts** **certain classes** or classes that **implement specific interfaces** **Ex.** GenericList **only accepts classe**s that **implement both interfaces**
42
**How** are **generics** executed?
**Java Compiler converts generic type to instance of the** **Object class** Why not use Object class then? using the generic type gives us c**ompile time, type safety**! **But** at **compile time**, generic is converted back to **Object class** instance under the hood
43
What is **type erasure**?
**Java compiler** replacing all **generic types** at **run time** with **Object class** or **constraining classes / interface**s specified at run time!
44
**How** does **generic** w/ constraint **get executed by Java**?
All **instances** of generic type are **replaced** by the **constraint class or interface** **this is called type erasure.**
45
**What** is the c**omparable interface**?
A **generic interface** takes an **generic type**, **compares to another** **Ex.** Pass **type User** to comparable and implement **compareTo** method
46
**How** can we **rewrite** this code for the **comparable interface**?
47
**What** is a **generic method**?
A **generic method** inside a **non-generic class**
48
**How** can we **declare a class** with **multiple type parameters**?
add after class name declaration **add private** fields using **K and V** **add method** parameters using **K and V**
49
**How** can we implement **multiple type parameters**?
Use **K** for first **generic parameter** Use **V** for second **generic parameter** **Why?** We want to pass **two different type parameters** at compile time **Not the same parameter type** at compile time Ex. Key could be **integer**, value a **string** Or key could be **character,** value an **integer**
50
What is the **"?"** symbol?
**Wildcard character** **represents unknown type** **Java Compiler** creates an **anonymous type** under **the hood**
51
**How** can we **restrict** a **wildcard**?
**add** \<**?** extends **User**\> Now we can only pass a type of User or derivatives!
52
**What** does **adding the super keyword** after a **wildcard allow us to do**?
**add** to a list GenericList super User\> **JavaCompiler** treats unknown type like parent of User class, Object class
53
**When** we use the **extends keyword** with a **wildcard**, how does the **Java compiler treat it?**
**treats the class** after **extends as the parent class** Ex. GenericList extends **User**\> We don't have access to Capture class (?) **So**... we can **only read from** this list, **cannot add**
54
**What is** in the **collections hierarchy**?
**Green** are **interfaces** **Blue** are classes that **implement interfaces**
55
**What problem** does the **iterable interface** **solve**?
**Problem:** w/o **making items** in a **class public**, **cannot iterate over them** **outside** of the **class** **Poor solution**: Expose **items field** to **outside** (public) **Why not good?** **exposing internal implementation** of a **class to the outside** causes breaking changes in future class changes
56
**What** is the **iterable interface**?
An **interface** with a **few methods** **Why?** **clients** code **against iterable interface (buttons)** **Solves?** Can iterate over an object without knowing internal implementation preventing class dependency **How?** add ***implements Iterable*** to class declaration **iterator ( )** - returns an iterator object (can iterate this object)
57
**What** is the **forreach loop**?
**Syntactical sugar** over **iterator object** **java compiler** **converts** code to **use an iterator object**!
58
**How** do we **implement** ou**r list** **iterator**?
1. **Make list iterable** by **implementing iterable iterface** (add to class declaration signature) 2. Implement the **iterator ( ) method** - returns an iterable object 2. Create the **private class** of type Iterator - the object returned by the iterator ( ) method **Why?** has intimate knowledge of the internal elements **implement hasNext() , next ( ) methods!** **knows how** to **iterate over our GenericList list** **Can access private fields within our GenericList class**
59
**How** can we pass **multiple elements** to be **added in a collection**?
Use **Collections interface** static method **addAll**
60
**What** is the **collection interface**?
A **collection** represents an **object that acts as a collection** or container for other objects! represents a **group of objects**, known as its ***elements***. Some collections allow **duplicate elements** and **others do not**. Some are **ordered** and **others unordered**. The **collection interface** doesn't **implement** **indexing**! **Operations**: **add** - ensures collection contains the specific element **remove** - removes a single instance of a specific element from collection **size** - returns number of elements in collection **contains** - returns true if collection contains specific element
61
**How** can we **convert a collection** to a **regular array**?
**.toArray( T [] )** pass array type or **default** returns **Object []**
62
**How** can we check if **two collections** are **equal?**
Use the **.equals method** **Why?** == operator will compare hashCode not values
63
**What** is the **list interface**?
**implements** the **collection interface** but allows us to access objects by index! **list interface** represents an **ordered collection** (sequence) can **access objects by indexes** **Parent** **Collection** Interface - don't care about indexes, only adding and removing objects **List interfaces:** allows us to work with **ordered collection**, access **objects using index** **Implementing Classes:** **ArrayList - dynamic array** **LinkedList - linked list**
64
**What** is the **error** with this **implementation**?
We have **not implemente**d the **Comparable Interface** in our customers class! To use the **Collections** static **sort method**, we must implement the **Comparable Interface** in the **Objects** (Customer Class)
65
**How** do we **implement** the **comparable interface** to **use the** **static sort** method in the **Collections Interface**?
66
**How** can we use a **comparator object** to **sort data** using the **Collections interface**?
**Collections.*sort*** **parameter is overloaded** **pass a list** that **implements the comparable interface** and **a comparator object** **Why?** A **comparator object** can tell us **how to sort two objects**! Ex. Sort by email
67
**What** is the **queue interface**?
extends collection interface used to process jobs based on order recieved Ex. Printers receive jobs, process one by one **Implementation?** **ArrayDeque** - double ended queue **PriorityQueu**e - each item gets priority, determines position
68
**How** can we **use** the **Queue interface**?
**select** an **implementing class** (**ArrayDequeue**) use **it's methods:** **.add / .offer** **.remove / .poll**
69
**What** is **unique** about the **Set interface**?
only allows **unique entries** (guarantees uniqueness) does not **guarantee order**! (do not rely on for order) **remove duplicates?** put a collection into a set, only unique value remain **parameters?** overloaded - can pass collection of strings! **Implementation?** **HashSet\<\>( )** - 90% of the time **operations?** **.union** - combination of two sets **.retainAll** - gives common items found in both sets .**removeAll** - gives items found in set1 that are not in set2
70
**How** can we use the **Set Interface t**o remove duplicates in a collection?
add them to the **set**! HashSet\<\>( ) overloaded parameters = can take a collection of strings!
71
**How** do we **combine two sets**?
use the .***addAll*** method **called** a **"union"** combines **two sets** and **removes duplicates**
72
C **How** do we find the **intersect**ion between **two sets**?
use the .***retainAll*** method gives items common in both sets
73
**How** do we get **all the items only found** within **one set and not in another**?
use the **.removeAll** method returns **all the items only present** in the **first set**
74
**What** is the **Map interface**?
Part of **collections framework** but **not part of the hierarchy** has **two generic type** parameters **Implementing class?** HashMap class **Ex**. Use **customer's email** as key, **customer object** as value Not an **iterable object**! .**keySet ( )** - returns list of keys .**entrySet ( )** - returns of Set of entries (key, value) pairs .**values ( )** - returns collection of customers
75
What's covered in this section?
**Lambda expression**s - functional programming (2014 Java \*) **Functional Interfaces** - consumers, suppliers, functions, predicates **Extremely important** **Master these** used in **real world applications**!
76
**What** is a **functional Interface**?
**An interface** with **only a single abstract method** ## Footnote **Used to represent functions** **Ex. Comparable Interface - .compareTo method**
77
**What** is an **anonymous** inner class?
A class **without a name**, **inside a method** **Why?** Sometimes, we **don't want to create a separate class** to **implement an interface,** this annonymous inner class is used **Lambda Expressions** are **SE 8 cleaner i**mplementation of this concept!
78
**What** is a **lambda expression**?
**Objects** that we can use to **represent** **anonymous functions** **Lambda expression:** ( ) parameters -\> lambda operator { } body of function
79
**How** can we make our **lambda expression** **cleaner**?
Exclude **type of parameters**, Java Compiler will fill it in! **remove parameter parentheses** (if single parameter) **remove braces** (if single line in body) **Why?** **Lambda expression** will be **checked** based on the **signature of the functional interface**
80
**What** can **we access** within **our lambda expressions**?
**local variables** in **enclosing method** **static fields** in **enclosing class** **Ex.** **prefix** is a **local variable** of the **enclosing method** **suffix** is a **static field** of the **enclosing class**
81
**What** else **can we access** in a **lambda expression**?
**instance fields** (non static fields)
82
**What** are the **differences** between **Annonymous inner classes** and **lambda expressions**?
**Lambda expression:** **.this** refrences the **current instance** of the **enclosing class** **references the enclosing object** **no instance fields (state)** **can only access static/instance fields in enclosing class** **Annonymous**: **.this** references current instance of annonymous inner class can have fields to store data
83
**How** can we reference a **consumer directly** using a **lambda expression**?
**Class/Object** :: **methodName** Ex. ***greet***(LambdasDemo::new); references **constructor** of LambdaDemo class ***greet***(LambdasDemo::print) references **static method** of LambdaDemo class ***greet***(demo::printAnother) references **instance method** of **demo object**
84
**What** methods can we **reference** with a **lambda method reference**?
**Static and instance** **methods** and **constructors**!
85
**How** many **types of functional interfaces** do we have in **Java**?
**Four types** used to perform **common tasks:** **Consumer** - **void** - operation that takes single operation, returns no result (consumes a value) **Supplier** - **value** - akes no input, returns a value (supplies a value) **Function** - **map** - maps a value to a different value **Predicate** - **boolean** - takes an object, checks if it fulfills a criteria \*\*defined in **Java.util.function**
86
**What** are **consumers**?
**functions that take arguments, do some logic but do not return a value (void return type)**
87
**What** are other **consumer interfaces**?
**takes args**, returns void **BiConsumer** - takes two arguments **IntConsumer** - takes integer consumer **DoubleConsumer** - takes double consumer
88
**How** do we write this **imperative programming** in **declarative programing paradigm**?
89
**What** is **Imperative programming**?
A **style or programming** that specifies **how logic should be implemented.** Ex. using for, if/else, switch/case
90
FI **What** is **declarative programming**?
A **programming style** that **specifies what** needs to be done and **omits how it should be done**
91
**What** does **chaining consumers** mean?
running **one function** **after the next** in **series (sequence)**! Ex. .**andThen**
92
**What** is a **supplier**?
**Function** that **doesn't take an input** but **returns a value**!
93
**What** is **lazy evaluation**?
**function** not executed **until** we **specifically call it** **value** is **not generated until specifically asked**
94
**What** is the **function interface?**
represents **a function**! Takes **a parameter**, **returns a value** **#1 arguments have type, return is generic** **ex.** IntFunction - takes integer, returns R **#2 arguments are generic, return has type** **ex.** ToIntFunction - takes generic, returns integer #3 **Arguments and Return are types** ex. IntToLongFunction - takes integer, returns long
95
**What** is **one way** to build a **multi-step** function using the **Functional interface**?
use the .**andThen**
96
**What** is **another way** to **write this declarative statement**?
97
**What** is the **predicate interface?**
**extremely useful** **tons** of **real world applications** used to **filter data!** **give generic args**, **returns boolean** Ex. give Customer obj, check if have a balance **Specialization?** **BiPredicate** - takes two args, returns boolean **intPredicate** - takes integer, returns boolean
98
**How** can we **combine predicates** to **test multiple conditions**?
**.or** = || operator **.and** = && operator **.negate** = ! operator
99
**What** is the **BinaryOperator Interface**?
A **special type of function** takes **two generic args**, returns **two generic args** **Specializations?** **IntBinaryOperator** - takes two integers
100
**What** is the **UnaryOperator Interface?**
a **function** that **takes generic arg**, **returns generic result**
101
**What** is **covered** in the **stream section**?
**streams** = **ways to access collection**s **declaratively!** **Stream operations used to create sophisticated queries like...** **mapping, filtering, slicing, sorting, reducing**
102
**What** are the **key difference**s between **Imperative and Declarative** **programming paradigms**?
**Imperative:** statements specify "**how**" to do something **stated clearly** and **in detail**, leaving **no room for confusion** or doubt **Declarative:** statiements specify **"what"** to do **without** requiring the **programmer to specify an exact procedure** to **be followed**. **Ex.** **SQL** - **Declarative Language** - SQL Queries **specify "what"** we to do, but we **don't write logic for "How"**
103
**Why** were **streams built** in **Java**?
To **allow** us to **process collections** in a **functional (declarative)** way! **Allows** us to **build data processing lines** Makes our **code cleaner!** Makes our **code easier to read!**
104
**What** is **functional programming**?
A **special type of declarative programming** with a few special **features**!
105
**What** **two types** of **stream operations** are there?
**Intermediate** and **Terminal** **Intermediate Operations:** Return a new stream can continually transform stream **Terminal Operations:** if don't call terminal operation, nothing happens actual operation happens after calling method
106
**How** can we **build data processing** lines **using streams**?
107
What are **intermediate operations**?
allow us to **build and customize processing** pipelines!
108
**What** are **reducers**?
**Reduce** a **stream of objects** to a **single object** (answer) **These** are **terminal operations**! **Count** - count elements in a stream **matchers** - can see if any or all elements satisfy a condition **find** - get element in stream **max/min** - find element based on comparision
109
**What** are the **four methods** for **slicing a stream**?
**limit(n)** - limit number of elements in stream **skip(n) -** can skip elements in stream, paginatino **takeWhile(predicate)** - as long as condition, keep taking elements
110
**How** can we **create streams**?
**Collections** have **.stream ( )** method + **derivative classes** (List, Queue) **Arrays** util class has **.stream ( )** method
111
What does **every stream have**?
**.forEach** method iterates over items
112
**How** can we **create an infinite number** of **streams**?
**create** a stream **call methods** on the stream **terminate** the stream Ex. **give** the .***generate*** method a **Supplier**
113
What does .**flatMap** allow us to do?
Allows us to work with **individual items in a stream** allows us to **flatten a stream** Ex. We want to flatten lists to work with individual numbers
114
**How** can we make this **code cleaner**?
**extract predicate** to a **separate method**
115
**How** does the **.limit metho**d work?
**allows** us to **limit number of items** in our **stream**
116
**How** does the **.skip method work**?
can **skip elements** in our collection **that come out in our stream**
117
**How** can we **use streams** to **create pagination**?
118
**How** is the **.takeWhile (predicate)** method different than the **.filter** method?
**.takeWhil**e stops the moment predicate condition is not true, even if elements after would fit condition **.filter** iterates our entire collection before stopping
119
**What** is the **.dropWhile(predicate) method**?
**escapes all elements** that **match predicate criteria**
120
When do we use the **Comparator interface** vs the **Comparable Interface**?
Implementing a **comparable Interface** couples the **compare method** to the **implementing class** This has limitations! if we want to **sort by a different parameter**, we **should implement comparator interface (using lambda expression)** **why?** **extract the compareTo method by using a** comparator **object! (annonymous object, lamda expression)**
121
**How** can we **use streams** to **sort data**?
1. Rely on **type class** to implement **comparable interface** 2. Pass a **comparator object** to the **sort method (use lambda expression)**
122
**How** can we **re-write this code**?
123
**How** can we **reverse** the **order of elements** in our stream using the **Comparator interface**?
**Comparator** has a **default method** called **reversed**!
124
**How** do we get **unique values** in a **Stream**?
map( ) **distinct ( )** .forEach ( )
125
**How** do we **trouble shoot** complex **query issues** with **streams**?
use the **peek method to get output of each operation**
126
**What** are the **matcher operations?**
127
**What** are the **find operations**?
128
S **How** does the **general purpose reducer work**?
reduces **a stream** to a **single value**
129
**How** can we **re-write** this **lambda expression**?
130
**How** else can we **re-write** this **lamdba expression**?
**.reduce method** includes an **option to pass an identity value** (initial value) **Why?** **don't have to work** with an **Optional object** (if stream is empty)
131
**How** do we **collect** the **result of a stream** into a **list, set or hash map?**
.**collect** method **takes** a **collector object** **(Collector is an interface)**
132
**How** can we **rewrite** this **lambda** using **a method reference?**
133
**How** can we **return movie objects** as the **values** in our **collector hashmap**?
**Function.identity ( )** takes an object and returns the object
134
**How** can we get the **sum of values** in a **collection**?
**Collector.summingInt**
135
**What** is **Mosh's favorite collector** and **why**?
.summarizingInt **Why?** **gives us statistics about values in stream** it's **very useful** in **buidling real world applications**
136
**What** is the **joining collector**?
used to **concatinate values** in a stream **based on a delimiter**
137
S How do we **classify or group** our **data using streams**?
**Collectors** interface has a **groupingBy ( ) method** **groupingBy** takes a **classifer** **classifer** is a **lambda function** **returns Hashmap w/ key = genre : value = List**
138
**How** can we map our **groupingBy method** to a **list, set or map?**
**Collectors.groupingBy** is **overloaded** can pass **another argument** **Collectors.toSet / Collectors.toList / Collectors.toMap**
139
**How** can we get the **number of movies** in **each genre** using **lambdas**?
140
**How** can we using **groupingBy** to **display the titles** of all **movies within each genre**?
**Collectors.mapping** is overloaded **takes two args :** mapping function, Collectors.joining
141
**How** do we **partition (separate)** data **using streams**?
**partitioningBy** can take **two arguments**: **#1** **Predicate** - condition function #2 - **Collectors.mapping**
142
**How** do **we work** with **primitive type streams**?
**Use specialized streams:** **IntStream, LongStream, DoubleStream** **Useful methods**: **rangeClosed** - upper bound is included **range** - upper bound is excluded
143
**What** is **concurrency**?
leveraging **multi-core processors** Why? Most devices **have multiple cores** make **applications faster, more responsive**
144
**What** is **covered** in the **concurrency section?**
**Processes/threads** starting, stopping, pausing threads **race conditions, visibility challenges** **solns.** **synchronization, volatile fields, atomic objects**
145
**What** is **a process?**
an **instance of a program / application** OS loads application **inside a process** **Process:** contains **resources**, **memory** and **image of the applications** **code**
146
**How** many **processes** can your **operating system execute** at **the same time?**
Many! run antivirus, play music! **Process level concurrency!**
147
**What** is a **thread?**
A **sequence of instructions!** That **thing that executes your code** Can build **many threads!** **Each process can have additional threads to run tasks concurrently!**
148
**What** is an **example of currency** using **threads?**
A **web application** that **has multiple threads** for **concurrently dowloading images**
149
**What** does **multi-threaded** applications **leverage?**
**Multiple cores** each **device now contains!** without **multiple threads** essentially **using only one core!** **Wasting three other cores** for **concurrent processing!**
150
How many **cores does** my **MacBook Pro have**?
have **two cores available** **each core can run two threads** **Program is using two threads:** **main thread**, **garbage collector**
151
**What** is the **most important thing** we need to **know how to do with threads?**
**Safely share data between threads** **Why?** if **two threads** try to **change data at the same time**, crazy **things happen**
152
**Why** should **we learn** about **threads and concurrency**?
To **exploit** **parallel hardware** ## Footnote **multiple cores in each machine**
153
**What** is the **interface Runnable**?
**Represents a task to be run on a thread** **abstract method:**.run
154
**What** **happens** after a **thread excutes a task?**
**it dies** - we **don't need to worry about it**
155
**How** do **threads start and run?**
**In parallel** Ex. **Downloading 10 files concurrently** using **10 threads!**
156
**What** does **multi-threading** make our **applications?**
**Faster and more responsive!** **Ex. each task takes 5 seconds, run concurrently** **vs. one after the other takes 50 seconds!**
157
**What** is a **thread scheduler?**
if **there are more threads** to be executed **than processors!** **thread scheduler** toggles **threads w/ CPU time**
158
**What problem** does **joining threads solve**?
**running threads sequentially** **how to know when one thread finishes?** thread **execution time is variable!** **cannot use thread.sleep!** Soln: **wait for completion of prior thread** **blocks next thread until prior thread finished**
159
**What** is the **problem** with the **.join method?**
**causes current thread to wait** during wait time, thread cannot perform tasks! Ex. if **Main thread is paused**, **cannot respond to UI events**
160
**What** **problem** does **interrupting a thread solve?**
**allow user** to **cancel a long lived thread**
161
**What** does the **interupt thread actually do?**
**sends a request** to the **thread to stop** it's **up to the thread** whether to **respond or not!** **Soln**: Check for **interupt request**, **handle accordingly!**
162
**What happens** if we **try to interupt a thread** that is **sleeping?**
it **throws** an **exception** **Soln:** handle the exception
163
What **happens** with **thread in real life?**
They **may need** to **access or modify** the **same resource**
164
What **happens** when **multiple threads** try to **update data at the same time?**
It's **not going to work**! We **get wrong results**, **applications may crash!** **This is called race condition!**
165
What is a **race condition?**
When **multiple threads** try to **modify a shared resource** (data) **at the same time!** **Why?** **Threads are racing** to update data first
166
**What** is a **visibility problem**?
When **one thread** updates **a shared resource** and **the changes are not visible to other threads** who **may need to access this data!** ## Footnote **Reading from shared resources is fine!**
167
**How** should our **multi-threaded systems** be **designed?**
using **thread safe code:** **code** that can be **safely executed** by **multiple threads in parallel** Ex. **some classes** are **thread safe!** They can be **executed across multiple threads** in **parallel**
168
**What** is a **non-atomic operation?**
an **operation that involves multiple steps.** ex. **totalBytes++** **Step 1** - fetch value, move to CPU **Step 2** - increment value **Step 3** - store value in memory
169
**What** are **strategies for thread safe code**?
1. **Confinement** - don't share data across threads, restrict each thread to it's own data, after process, combine results 2. **Immutable** - sharing immutable data is fine, can only read data in threads, data cannot be changed after object is created 3. **Synchronization** - prevent multiple threads from accessing objects concurrently using locks, forces code to run sequencially 4. **Atomic objects** - allow us to avoid locks, increment atomic operation into one step 5. **Partitioning** - partition data so multiple threads can access only a specific segment in the collection.
170
What is an **example of a race condition**?
Each **download file updating** the **status data object**
171
**What** is a **lock?**
**Synchronization technique:** **lock certain parts of code** only **one thread at a time** can **execute locked code** **other threads** have to **wait**
172
**What** are the **problems with synchronization?**
1. Locks f**orce code to run sequentially - not concurrently** 2. It's **challenging and error prone** 3. **Deadlocks** - one **thread waiting for another thread forever** **Synchronization is bad (generally)!** **avoid it!**
173
**How** can we use **confinment** to **prevent race conditions**?
**remove global status object** each thread works with **own status object** instead of **each thread working** with a **single global status object (incrementTotalBytes( ) )** **-remove status object parameter from DownloadFileTask ( )** **-add new DownloadStatus ( ) to constructor of DownloadFileTask** **-ask each thread for total bytes, combine them across objects**
174
**How** do we **prevent multiple threads** from **accessing objects** at the **same time?**
**Using locks!** **Coordinate access** to **critical section** code is executed sequentially this is synchronization
175
What is **Lock interface** and what are the **implementing classes?**
Java.concurrent.locks package
176
**How** can we use **locks to prevent race conditions?**
177
**What** is the **synchronize keyword?**
Allows us to **achieve synchronization** without explicitly **locking and unlocking resources** **code is simpler!**
178
**What** is the **problem** with using **.thi**s as the **monitor object** in our **synchronized code block?**
every object has a **lock method** (under hood) .this uses the current objects lock method **Why?** both methods are using the same monitor object only one object can access synchronization on object prevents **us from accessing other fields** that are not being executed reduces **throughput of this API** **Soln?** **Dedicated monitor objects**
179
**What** are **dedicated monitor objects**?
**Best approach** Used with **synchronization codeblock** Instances of **Object class** used to **lock data**
180
**What** is **another way** to use the **synchronized keyword**?
**Problems:** uses the .this lock method this causes issues with accessing other fields **Soln:** Use dedicated monitor objects
181
**What** is a **best practice** for **synchronization**?
Don't use it in new code understand it for legacy applications **Why?** It causes issues, reduces concurrency
182
**What** is the **volatile keyword**?
Solves **visibility problem** NOT **race condit**i**on** It **ensures if one thread changes data**, other **threads can see changes**
183
**What** is the **visibility problem?**
**New threads** cannot **see changes** of a **shared resource (peice of data)** **Ex. Thread2** cannot see that the isDone variable in the status object was updated to true, so it **hangs indefinetly waiting**
184
**What** is **underlying** the **visibility problem?**
**Two cores** each **running a thread** **each core** contains **local cache memory** **RAM values** are read **into each core's cache memory** one core **updates value locally, other cannot see cache value** **even if it returns** cache **value to RAM** **second core** has a **previous copy** in **cache**
185
**What** does the **volatile keyword** tell the J**ava Virtual Machine?**
Always **read** value from **RAM memory** Don't **rely on cache value** **Update RAM** memory **immediately** the **field is volatile**
186
**How** can we **implement wait ( )** and **notify ( )** in Java?
Every object has the **.wait** and **.notify** methods! **Inherited** from Object class Wrap in **synchronized block** **BUT** **Don't use these in new code!!** **We have better implementations currently**
187
**What** is the problem with this **wait ( ) state implementation** using a **while loop?**
**Empty while loop!** **While loop** is **continuously running**, until condition is true could run **millions or trillions** of times **wastes CPU cycles**
188
**What** are **atomic objects**?
allow us to **update counter variables** concurrently! use these with **counter variables!**
189
**Which** is better to use **atomic types** vs. **adders**?
adders are **faster**! It's **better** to **use adders**
190
What are **adders?**
If you have **multiple threads** updating **values frequently** Use **adder classes:** LongAdder, DoubleAdder **Why?** they're **faster** than **atomic objects** **store counter values in array cells!**
191
**How** do **adders work?**
**keeps an array of counters** that can **grow on demand** **array cells**, each **holding a counter value** **threads** can **update cells concurrently** .**intValue ( )** - adds all counter values and returns result
192
**What** is the **synchronized Collections**?
**Wrapper** around **collections class** **static factory methods** - creating synchronized Collections Ex. **Pass object** that implements collections **method wraps** ArrayList in **synchornized collection** **add ( )** , **remove ( )**, etc has **synchronized code**! Makes a **regular list synchronized**
193
**How** can **multiple threads** share **a collection**?
Collections.**synchronizedCollection** ( ) **Pass lambda** to **Thread constructor:** Can use **lambda expression** to represent a **runable object** **Runable interface** is a **functional interface**
194
**How** do **synchronized collections** achieve **thread safety**?
Using **locks** ## Footnote **entire collection gets locks, other threads have to wait** **can have negative impact on performance and scaleability!**
195
**What** are **concurrent collections?**
**Faster** than **synchronized collections** **use partition technique** to **allow thread safety** **divide** **collection into segments** only **one thread at a time** can **access a segment**
196
**What** is the **Executor Framework?**
Higher **level abstractions** used for **building concurrent applications** released by Java SE 5 **let's java** worry about **handling thread manipulaton**
197
**What** is covered in the **Executive Framework**?
Thread pools Executors Callable and Future Interfaces Asynchronous Programming Completable Futures
198
**What** are some of the **challenges** of **working directly** with **Threads?**
**Availability** - we have a limited number of threads. May end up creating too many threads lead to out of memory errors! **Costly** - creating and removing **threads is costly.** If we have to repeatedly create new threads to execute many takes, this requires **creating threads repeatedly!**
199
What is a **Thread Pool?**
Java 5 solution: A pool of threads called worker threads **can we re-used to execute multiple tasks** **not destroyed and recreated** **after execution**, they're returned to the **thread pool** **thread pool assigns tasks to threads** **additional tasks stored in queue until re-usable threads are available**
200
**How** are **thread pools** represented in **Java?**
Using the ExecutorService interface **Implementation:** **ThreadPoolExecutor** - most common use **ScheduledThreadPoolExecut**or - schedule tasks **ForkJoinPool** - divide and concur recursion
201
**What** is the **Executors class**?
**Static factory methods** for creating **instance of ExecutorService** implementations **Better** than creating instances **directly.** Ex. **Executors.newFixedThreadPool** ( ) - will **create an instance** of **ThreadPoolExecutor** class Ex. **Executors.newScheduledThreadPool** ( ) - creates instance of **ScheduledThreadPoolExecutor**
202
**How** do we use the **Executors class?**
**.submit ( )** task to **thread pool** don't have to **explicitly assign task** to a thread
203
**What** must we **explicitly** do **when working** with **thread pools**?
**Terminate them!** **.shutdown ( )** **.shutdownNow( )** Surround in **Try Catch block**
204
**What** doesn't the **executor framework** not **protect us against?**
**Concurrency issues** - **race conditions**, **visibility conditions** ## Footnote **It just simplifies thread manipulation!**
205
**What** is the **best practice** for **shutting down ExecutorServices?**
**Try-catch** with **finally block** **Why?** If our **try code block** throws **an exception** We still **shutdown the ExecutorService** and **allow our worker thread to continue** with other tasks
206
**What** is a **future object**?
**Future Interface** **Represents** an **operation** that **will complete in the future** **Result** of operation **not calculated immediately** with **CPU** We can **get the future result** of **an operation** **Problem?** It's a blocking operation **.get ( )** will block current thread until future operation is completed
207
**What** is the **callable interface**?
Used to **return a value** from **a thread** How? Pass **a callable** to the **Executor.*submit*** method
208
**How** does **Java execute** a **future callable?**
immediately returns a future object future object represents result of operation We can call method on this object **.get** - get value of operation, time out operation **.cancel** - cancel an operation **.isCanceled** - check if cancelled **.isDone** - check if done
209
**What** is **asynchronous programming**?
Writing **non-blocking** code **Why?** Making current thread **wait for the completion** of another thread (future object) wastes our threads! Ex. **Android App** - main thread **handles UI events** (clicks, keystrokes) if **main thread has to wait** to completion of other threads, it cannot respond to UI events, **application window will freeze**!
210
**What** is the **Interface CompletionStage**?
**Allows** us to sequence **various operations** in a **declarative way** Ex. We can **string declarative methods** together like we did with **filtering and mapping data** in **streams** Why? **Many asynchronous** tasks **may require multiple steps** **Here** was can **string steps together** using the **CompletionStage interface!**
211
**What** is the **CompletableFuture** class?
2014 Release by Java **Handle Asynchronous applications** **​Used to build complex, asynchronous applications!** Implements **Future Interface** Can **explicitly** complete **future object** **.runAsynch -** don't have to create an executor, call the .submit and shut it down .**supplyAsych** - function that returns a result
212
**What** does the **CompletableFuture** class **allow us to do**?
Create threads **asynchronously** Do **not need to create an executor,** **submit task**, **shut down** **.runAsynch** - returns void future object **.supplyAsynch ( )** - pass suplier that returns a value, can also pass an executor object, if none common pool used
213
**How** can we create a **future completable object?**
Use the **CompletableFuture class** **.supplysynch** - takes a supplier function, returns a future object that we can .get value **.runAsynch** - pass an instance of the Runable interface, returns a future void object
214
**What** is a **powerful technique** that **we should start** using in our **applications right away**?
**Asychronous API** **How?** **Wrap** a **synchronis method** inside a **CompletableFuture object**
215
**When** we are working with a **long running operation** like **querying a database, calling a remote service, working with a file system** how **should we run them?**
**Run on a separate thread**, not Main thread! ## Footnote **Asynchronously!** **How?** **Wrap a synchronis method inside a CompletableFuture object**
216
**What** is the **convention** for **naming asynchronous operations?**
add -***asynch*** suffix
217
**How** can we **execute a code bloc**k after **an asynchronous operation** completes?
using the **.thenRun** or the **.thenRunAsynch** provided by the **CompletionStage interface** in **CompletableFuture class** **.thenRunAsync - runs function on a separate thread** **.thenRun - runs function on main thread**
218
**How** is this **code** going to **be executed**?
**.submit** method is going to **start the task on a separate thread** and **return it as a future object.** **then**, when we call **future.get ( )** we **have to wait** for this **operation to complete** on the **separate thread**
219
**How** can we implement an **asychronous API method?**
Wrap it in a CompletableFuture object **why?** It'll start on a separate thread and not block current thread
220
**What** is the .**thenAccept** method in the **CompletableFuture** **class**?
**get result** of **completable future** takes **a consumer object** **(takes obj. doesn't return value)** **.thenAcceptAsynch** - runs new code on separate thread **.thenAccept** - runs new code on main thread
221
**How** can **we recover** and **provide a default value** when **handling exceptions?**
**recover** from **an exception** by **transforming it** into **a value** **Use the .exceptionally method!**
222
**Where** does the **exception get thrown**?
In **a different thread** have to use **get method of the future interface** to **get it** and **bring it** into the **main thread**
223
**How** can we **map** the **result** of a **future object** to a **different data type?**
.**thenApply** **( )** pass a **map function**
224
**How** can we **make this code better**?
**Benefits of CompletableFutures:** **Complex** **async applications** in **declarative way!**
225
**How** do we **start a task** on the **completion of another task?**
**CompletableFutures** **.thenCompose ( ) - pass a function that represents a new completable future (async task)** Ex. Have a user 1. read user email from database 2. pass email to music streaming website to get playlist
226
**How** can **we make** this **code better?**
Extract **getUserEmail** into a **separate method that returns a CompletableFuture** ## Footnote **Can build complex asyc operations in a declarative way!** **The beautfy of CompletableFutures**
227
In **Mosh's opinion** what is one of the **most powerful abilities** of **CompletableFutures**?
**The ability** to start **two tasks asychronously**, then **combine the results** **.thenCombine - non-blocking method** **Ex.** Start **two tasks concurrently**, **combine results**
228
**How** can we **start two tasks concurrently** then **combine their results?**
**Build** a **processing pipeline** **declaratively** using **CompletableFutures**!
229
**How** can we **wait** for the **completion of many tasks** before **doing something else**?
**CompletableFuture** **.allOf() -** pass var args, wait for completion for all tasks **.thenRun()** - pass runable object **.get ( )** - get result of individual CompletableFuture obj
230
**How** can we get the result of **the first task that completes when running two tasks concurrently?**
Call both services **concurrently** **CompletableFuture.anyOf ( )** - returns a new CompletableFuture as soon as any task completes
231
When **calling a remote service** what do we **want to have**?
**A limit** for how **long to wait** **Don't** want to **wait forever!** **.orTimeout ( ) -** returns a new completableFuture that times out after a specific time **.completeOnTimeout ( ) -** returns a new completableFuture after specific time
232
**What** is a **better approach**?
**Recover** with a **default value** ## Footnote **.completeOnTimeout ( ) - returns a new completableFuture after specific time**
233
**How** do we look at **return types** in **IntelliJ**?
**F1**
234
**How** can we **refactor this code**?
**Return** a stream from **FlightService**!
235
**How** can we **create an asyc application** that **uses Streams** and **CompletableFutures** to **query an API** and **return flight prices?**