Java_advanced Flashcards
What does this course cover?
Topics advanced Java developers use a daily basis.
Designed as a step by step guide and reference.
Each section builds on top of itself.

What are the requirements?
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!

What is covered in the exceptions section?

What is the root cause of many problems in Java programs?
NullPointerException
A class declared in java.lang package
What is an exception?
An object that contains information about an error
Several exception classes
What should a good Java developer anticipate?
Exceptions and handle them!
What are the three types of exceptions in Java?
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
What are checked exceptions?
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

What are unchecked exceptions (run time exceptions)?
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

What are errors?
errors resulting from problems external to our application
Ex.
StackOverFlowError
OutOfMemoryError
Source?
Infinite looping, JVM issues
Solve?
Let application crash, identify error source

What is the stack trace?
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

What can throw an exception?
A method can throw an exception
or cause of chain of exceptions
What is the exceptions hierarchy?

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

What will Java run time compiler do when a method throws an exception?
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
E What is the proper way to handled checked exceptions?
Catch exceptions using try-catch blocks!

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

How do we catch multiple types of exceptions?
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 can we refactor these exceptions?

Combine the two exceptions using a vertical bar
block will catch exceptions of type IOException or ParseException and handle them the same

What is the finally block?
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!

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

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 can we throw an exception?
Use the throw keyword!

What is defensive programming?
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

When is it better to use defensive programming?
- When building a library for others to use
- 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 do we specify that our method may throw an exception so that the receiving class can handle this exception?
Add the throws keyword after parameter declaration

details represent API of this method
Why and how do we re-throw an exception?
Why?
Our application handles the exception 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!

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
What is the naming convention for Exceptions Classes?
Exceptions -suffix to name our Exceptions Classes
Ex. InsufficientFundsException
How do we create a custom exception?

Naming -Exceptions for suffix
add extends + parent class name

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

What is a simpler way to chain exceptions?


What are generics?
One of the most important topics in Java
Why?
Many collection classes are implemented using Generics
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?
Generics - They offer polymorphism to collections

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)
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

What are the benefits of generics?

- Compile Time, Type Safety - provides compile time errors that ensure all objects are of the specified data type
- Cleaner code - don’t have to explicitly cast return types

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
What is boxing?
Java run time compiler will take a primitive value and wrap it in a wrapper class (reference type)

What is unboxing?
Java compiler extracts value stored in Integer reference type
can be then stored in a primitive type variable

How do we implement type constraints in a generic class?

add extends keyword + type
Ex. extends Number>
Can only use generic with Number class or any derivative classes (Integer, Float, etc.)

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

What is a bounded type parameter?
A generic that only accepts certain classes or classes that implement specific interfaces
Ex. GenericList
only accepts classes that implement both interfaces

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 compile time, type safety!
But at compile time,
generic is converted back to Object class instance
under the hood

What is type erasure?

Java compiler replacing all generic types at run time with Object class or constraining classes / interfaces specified at run time!

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.

What is the comparable interface?
A generic interface
takes an generic type, compares to another
Ex. Pass type User to comparable and implement compareTo method

How can we rewrite this code for the comparable interface?


What is a generic method?

A generic method inside a non-generic class

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

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

What is the ”?” symbol?

Wildcard character
represents unknown type
Java Compiler
creates an anonymous type under the hood

How can we restrict a wildcard?
add <? extends User>
Now we can only pass a type of User or derivatives!

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

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
What is in the collections hierarchy?
Green are interfaces
Blue are classes that implement interfaces

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
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)

What is the forreach loop?

Syntactical sugar over iterator object
java compiler converts code to use an iterator object!

How do we implement our list iterator?
- Make list iterable by implementing iterable iterface (add to class declaration signature)
- Implement the iterator ( ) method - returns an iterable object
- 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

How can we pass multiple elements to be added in a collection?
Use Collections interface static method addAll

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

How can we convert a collection to a regular array?
.toArray( T [] )
pass array type
or
default returns Object []

How can we check if two collections are equal?
Use the .equals method
Why?
== operator will compare hashCode not values

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

What is the error with this implementation?

We have not implemented 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)

How do we implement the comparable interface to use the static sort method in the Collections Interface?

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

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
PriorityQueue - each item gets priority, determines position

How can we use the Queue interface?
select an implementing class (ArrayDequeue)
use it’s methods:
.add / .offer
.remove / .poll

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
How can we use the Set Interface to remove duplicates in a collection?
add them to the set!
HashSet<>( ) overloaded parameters = can take a collection of strings!

How do we combine two sets?
use the .addAll method
called a “union” combines two sets and removes duplicates

C How do we find the intersection between two sets?
use the .retainAll method
gives items common in both sets

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

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

What’s covered in this section?
Lambda expressions - functional programming (2014 Java *)
Functional Interfaces - consumers, suppliers, functions, predicates
Extremely important
Master these
used in real world applications!

What is a functional Interface?
An interface with only a single abstract method

Used to represent functions
Ex. Comparable Interface - .compareTo method
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 implementation of this concept!

What is a lambda expression?

Objects that we can use to represent anonymous functions
Lambda expression:
( ) parameters
-> lambda operator
{ } body of function

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

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

What else can we access in a lambda expression?
instance fields (non static fields)

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
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

What methods can we reference with a lambda method reference?
Static and instance methods and constructors!

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

What are consumers?
functions that take arguments, do some logic but do not return a value (void return type)
What are other consumer interfaces?
takes args, returns void
BiConsumer - takes two arguments
IntConsumer - takes integer consumer
DoubleConsumer - takes double consumer
How do we write this imperative programming in declarative programing paradigm?


What is Imperative programming?
A style or programming that specifies how logic should be implemented.
Ex. using for, if/else, switch/case

FI What is declarative programming?
A programming style that specifies what needs to be done and omits how it should be done

What does chaining consumers mean?
running one function after the next in series (sequence)!
Ex. .andThen

What is a supplier?
Function that doesn’t take an input but returns a value!

What is lazy evaluation?
function not executed until we specifically call it
value is not generated until specifically asked

What is the function interface?

3 Arguments and Return are types
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
ex. IntToLongFunction - takes integer, returns long
What is one way to build a multi-step function using the Functional interface?
use the .andThen

What is another way to write this declarative statement?


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
How can we combine predicates to test multiple conditions?
.or = || operator
.and = && operator
.negate = ! operator

What is the BinaryOperator Interface?

A special type of function
takes two generic args, returns two generic args
Specializations?
IntBinaryOperator - takes two integers
What is the UnaryOperator Interface?

a function that takes generic arg, returns generic result
What is covered in the stream section?
streams = ways to access collections declaratively!
Stream operations used to create sophisticated queries like…
mapping, filtering, slicing, sorting, reducing

What are the key differences 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”

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!

What is functional programming?
A special type of declarative programming with a few special features!

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

How can we build data processing lines using streams?


What are intermediate operations?

allow us to build and customize processing pipelines!
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
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

How can we create streams?
Collections have .stream ( ) method
+ derivative classes (List, Queue)
Arrays util class has .stream ( ) method

What does every stream have?
.forEach method
iterates over items

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

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

How can we make this code cleaner?

extract predicate to a separate method

How does the .limit method work?
allows us to limit number of items in our stream

How does the .skip method work?
can skip elements in our collection that come out in our stream

How can we use streams to create pagination?

How is the .takeWhile (predicate) method different than the .filter method?
.takeWhile stops the moment predicate condition is not true, even if elements after would fit condition
.filter iterates our entire collection before stopping

What is the .dropWhile(predicate) method?
escapes all elements that match predicate criteria
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)

How can we use streams to sort data?
- Rely on type class to implement comparable interface
- Pass a comparator object to the sort method (use lambda expression)
How can we re-write this code?


How can we reverse the order of elements in our stream using the Comparator interface?

Comparator has a default method called reversed!

How do we get unique values in a Stream?

map( )
distinct ( )
.forEach ( )

How do we trouble shoot complex query issues with streams?

use the peek method to get output of each operation

What are the matcher operations?

What are the find operations?

S How does the general purpose reducer work?
reduces a stream to a single value

How can we re-write this lambda expression?


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)

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)

How can we rewrite this lambda using a method reference?


How can we return movie objects as the values in our collector hashmap?

Function.identity ( ) takes an object and returns the object

How can we get the sum of values in a collection?
Collector.summingInt

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

What is the joining collector?
used to concatinate values in a stream based on a delimiter

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

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

How can we get the number of movies in each genre using lambdas?

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

How do we partition (separate) data using streams?
2 - Collectors.mapping
partitioningBy can take two arguments:
#1 Predicate - condition function

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

What is concurrency?
leveraging multi-core processors
Why?
Most devices have multiple cores
make applications faster, more responsive
What is covered in the concurrency section?
Processes/threads
starting, stopping, pausing threads
race conditions, visibility challenges
solns.
synchronization, volatile fields, atomic objects
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

How many processes can your operating system execute at the same time?
Many!
run antivirus, play music!
Process level concurrency!
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!
What is an example of currency using threads?
A web application that has multiple threads for concurrently dowloading images

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!
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
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
Why should we learn about threads and concurrency?
To exploit parallel hardware
multiple cores in each machine
What is the interface Runnable?

Represents a task to be run on a thread
abstract method:.run

What happens after a thread excutes a task?
it dies - we don’t need to worry about it

How do threads start and run?
In parallel
Ex. Downloading 10 files concurrently using 10 threads!

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!

What is a thread scheduler?
if there are more threads to be executed than processors!
thread scheduler toggles threads w/ CPU time
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

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

What problem does interrupting a thread solve?
allow user to cancel a long lived thread
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!

What happens if we try to interupt a thread that is sleeping?
it throws an exception
Soln:
handle the exception

What happens with thread in real life?
They may need to access or modify the same resource

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!
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
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!

Reading from shared resources is fine!
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
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
What are strategies for thread safe code?

- Confinement - don’t share data across threads, restrict each thread to it’s own data, after process, combine results
- Immutable - sharing immutable data is fine, can only read data in threads, data cannot be changed after object is created
- Synchronization - prevent multiple threads from accessing objects concurrently using locks, forces code to run sequencially
- Atomic objects - allow us to avoid locks, increment atomic operation into one step
- Partitioning - partition data so multiple threads can access only a specific segment in the collection.

What is an example of a race condition?
Each download file updating the status data object

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
What are the problems with synchronization?
- Locks force code to run sequentially - not concurrently
- It’s challenging and error prone
- Deadlocks - one thread waiting for another thread forever
Synchronization is bad (generally)!
avoid it!

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

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

What is Lock interface and what are the implementing classes?

Java.concurrent.locks package

How can we use locks to prevent race conditions?

What is the synchronize keyword?

Allows us to achieve synchronization
without explicitly locking and unlocking resources
code is simpler!
What is the problem with using .this 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

What are dedicated monitor objects?
Best approach
Used with synchronization codeblock
Instances of Object class
used to lock data

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

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
What is the volatile keyword?
Solves visibility problem NOT race condition
It ensures if one thread changes data, other threads can see changes
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

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

What does the volatile keyword tell the Java Virtual Machine?
Always read value from RAM memory
Don’t rely on cache value
Update RAM memory immediately
the field is volatile
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

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
What are atomic objects?
allow us to update counter variables concurrently!
use these with counter variables!

Which is better to use atomic types vs. adders?
adders are faster!
It’s better to use adders
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!

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

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

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

How do synchronized collections achieve thread safety?

Using locks
entire collection gets locks, other threads have to wait
can have negative impact on performance and scaleability!
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

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
What is covered in the Executive Framework?
Thread pools
Executors
Callable and Future Interfaces
Asynchronous Programming
Completable Futures

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!

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

How are thread pools represented in Java?
Using the ExecutorService interface
Implementation:
ThreadPoolExecutor - most common use
ScheduledThreadPoolExecutor - schedule tasks
ForkJoinPool - divide and concur recursion

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

How do we use the Executors class?
.submit ( ) task to thread pool
don’t have to explicitly assign task to a thread

What must we explicitly do when working with thread pools?
Terminate them!
.shutdown ( )
.shutdownNow( )
Surround in Try Catch block

What doesn’t the executor framework not protect us against?
Concurrency issues - race conditions, visibility conditions
It just simplifies thread manipulation!
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

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

What is the callable interface?

Used to return a value from a thread
How?
Pass a callable to the Executor.submit method
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

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!
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!

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

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

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

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

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!

Asynchronously!
How?
Wrap a synchronis method inside a CompletableFuture object
What is the convention for naming asynchronous operations?
add -asynch suffix

How can we execute a code block 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

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
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

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

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!

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

How can we map the result of a future object to a different data type?
.thenApply ( )
pass a map function

How can we make this code better?

Benefits of CompletableFutures:
Complex async applications in declarative way!

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
- read user email from database
- pass email to music streaming website to get playlist

How can we make this code better?

Extract getUserEmail into a separate method that returns a CompletableFuture

Can build complex asyc operations in a declarative way!
The beautfy of CompletableFutures
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

How can we start two tasks concurrently then combine their results?
Build a processing pipeline declaratively using CompletableFutures!

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

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

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
What is a better approach?

Recover with a default value

.completeOnTimeout ( ) - returns a new completableFuture after specific time
How do we look at return types in IntelliJ?
F1
How can we refactor this code?

Return a stream from FlightService!

How can we create an asyc application that uses Streams and CompletableFutures to query an API and return flight prices?
