Part 4 - Java programming Advanced 2
Part 4 - Java programming Advanced 2
Advanced 2
1. GENERICS ................................................................................................................................................. 4
3. ENUMS .................................................................................................................................................. 24
4.1. THREADS................................................................................................................................................. 29
4.1.1. Introduction ................................................................................................................................ 29
4.1.2. Threads ....................................................................................................................................... 30
4.2. RACE CONDITION ..................................................................................................................................... 33
4.3. SYNCHRONIZATION (RACE CONDITION SOLUTION) ........................................................................................... 34
4.4. JAVA MEMORY MODEL (JMM) .................................................................................................................. 36
4.5. VOLATILE VARIABLES ................................................................................................................................. 39
4.6. ATOMIC VARIABLES................................................................................................................................... 41
One way to generalize it for there is by defining the type as Object class (the root
class and every other class extends from it)
Solution for this problem is to use generics types seed in this chapter. And
this the same code using generics
1.1. Generic type / parametrized type
❖ Generic type is simply a class or an interface with type parameters define in the
declaration
❖ Here is the basic syntax of generic type:
✓ the class name is followed by something called type parameters which are coma
separated
✓ they are enclosed in less then and greater than symbols
❖ Within the class type parameters (refer also as formal type parameter) can be used as:
✓ Type for instance variables
✓ Type for parameters and local variables within methods or constructors
✓ Method return types
❖ An example for generic class:
❖ Generic is compile time concept which means that generics does apply at runtime at
runtime there is not generics at all.
✓ Its means that a compiler basically uses feature called type Erasure and as name
call it’s erase a type so compiler going to remove type argument or type parameter
when write byte code (<String>, <T> for example) and replace all type parameter
in class definition with Object class. After compilation everything will be Object.
✓ A compiler would also insert explicit casting
✓ Type parameter cannot be used in static context for instance it cannot be used in:
➢ Type for static variables
➢ Static methods
➢ Static initialize
✓ If class is one of the bounds, then it must be first otherwise we get compiler error
✓ If first bound is class, then remaining bounds must be interfaces.
➢ In other word you cannot have more than one class in list of bounds
➢ You can have more than one interface and only interfaces too
✓ If bound is final class or enum then the type argument will be the bound itself
that’s because final class does not have subclasses and enum is essentially final
class too
❖ Item 23: Don’t use row types in new codes
✓ We should be not using row types
✓ Row type is a generic type without type argument. Its generic type but we have
instantiating it without any type argument
✓ Example 1 for row type (list):
✓ Problem with using row type is we would have the same behavior as we had
before generics was introduced that is compile time type safety is lost and we
want may runtime exceptions due to type safety problems
✓ Realistic example: comparative shopping engine which for given item fetch the
price information from multiple partner sources and this would allow to user to by
the item from the source that offer the lows price
➢ Instance of operator
❖ But parameterized type like generic type can also indicate that each type argument can be
an unknown type and that is done using wild card and here is an example
✓ Using “?” and it can be read as store of some type what this means is the method
go doesn’t know or doesn’t care whether you invoked with store of string or
double …
✓ Basically parameterized type is being gentrified here
✓ Also we can referenced to this wild card as unbounded wildcard
❖ Wild card can be used only as type argument so it cannot be used as type parameter
For instance is you used as type parameter like in this example than it would be
ambiguous to which of this 2 type parameter that data type of variable a is referencing
✓ Is can be used in assignment statement. it’s not commonly to see them being used
in this way
❖ Why cannot use Store<Object> instead of Store<?>:
✓ Limitation of using Object class of type argument would be that you can only
assign an instance that also has object as type argument (this is property called
invariance)
✓ But with wildcard we can assign an instance of any type like store of string or...
✓ Cannot invoke any methods of the parameterized type with those methods use the
type parameter of the class level in the method parameter
✓ The only way can invoke those methods passing null value as argument
✓ If try to do that you have compiler error
This example generate compiler error because we cannot assume the type of
elements in list 2 class, when we use it, we use type parameter of class level
1.4. Invariance
❖ We know that promise of generics is type safety at compile time, invariance is a property
that also helps with this
❖ Let’s consider hierarchy where book is subtype of bookmark, with invariance we have
this that is list of book is not subtype of list of bookmark
But if you assign other subtype of bookmark in array of book, you have array
store exception like this example
Difference between array and generics is generics insure type safety at compile
time itself while array insure that at runtime
❖ Item 25: Prefer lists to arrays
✓ If you feel type safety needs to be ensure at compile time then you should go with
list
✓ Arrays are important and have their place but it has type safety at runtime and we
know type safety at compile time is recommended.
✓ When method type parameter has the same name of class type parameter then,
method type parameter override the class type parameter when the method is
invoked. Like this example
✓ We can use method type parameter and class type parameter when they not have
same name like this example
If this method is static method, we have compilation error, because class level
type parameter cannot be used in static context it can only be used with
instances
✓ We can use bounded type parameter in method type parameter
✓ We can use class level parameter like bound in method level parameter when
method type parameter should be extended the class level parameter
✓ When can use as bound method type parameter but it should declared first like
this:
❖ Generic methods or even generic constructors can exist with or not the enclosing type is
generic
❖ Generic method invocation: type argument inference
✓ It can invoke just like regular non generic methods
✓ Only additional thing is specifying the type argument as we are dealing with
generics here
✓ Type argument can be either automatically inferred by the compiler or they can
also be explicitly specified in the method invocation statement
✓ Step1: let’s consider generic method like this
✓ Step 2 (automatically): when we pass double for example to this method the
compiler will consider automatically type argument like double (if type passed is
primitive, the type argument would be the box primitive type)
➢ If return type and both parameters use method type parameter, and if in
method invocation statement (first argument is string, second array list) in
this case type inferred will be the most specific common supper type
among the 2 arguments
➢ If you invoke method in the same class when you declared, you should use
this reference like this example
➢ If you are invoke generic method from super class you should use super
keyword
➢ Explicitly invoking generic method s rarely used. There are some cases
when you should use explicit invocation for example when type parameter
not present in method parameter or in returned type. In this case you
should use it
❖ With generics, kind of method overloading cannot works because at runtime, generics
type would removed
✓ Generic method with bounded type parameter: use generic method with bounded
type parameter
❖ You can use also lower bounded wildcard to allow all super classes of specified class to
be passes as type parameter in generic classes/methods by using super keyword
❖ Upper bounded wildcard has the same compiler type safety restrictions as an unbounded
wildcard that is:
✓ We cannot invoke methods that use class level type parameter with any argument
except null
✓ This means that you can only do stuff by passing input parameter x as producer of
data but does not consume data
❖ Lower bounded wild card is act as consumer of data and in the same time ensures that
compile time type safety is not compromised
✓ Can invoke methods that use class level type parameter only if argument is of
lower bounded type or one of its subtypes
✓ Example:
❖ Lower bound is only for wildcards cannot use it with type parameter
❖ Wild card ‘?’ can have only single upper or single lower bound (not like generic type
parameter they can multiple bounds)
❖ Class level type parameter cannot be used in static context. For instance it cannot be used
as type for static variables/static methods/ static Initializers
If static method needed generics then use generic methods
❖ We cannot overloading methods that will have the same signature after type erasure
❖ Generics and arrays do not mix them. For instance you cannot
✓ create an array of parameterized type
✓ In case of anonymous classes outer would still be outer. class and anonymous
would be outer$1.class
2.1. Non static Member Classes
❖ Non static member classes is used when the inner class object needs access to the
enclosing object so that it can access instance members So it has something to do with the
instance class
❖ It cannot be created unless the enclosing object is already created. So enclosing object is
created first then it is used to create the inner class object
❖ It’s simply an instance member of the enclosed object just like any instance member.
❖ So we can access to this class using <outer class name>.<inner class name> like this:
❖ Inner class object would maintain hidden reference to enclosing object and building such
hidden reference take subspace time
❖ Outer class object will not be garbage collected until inner class object is alive
❖ Common use of non static member class:
✓ To define an adapter. It used to produce different views of outer class object. For
example the collection views methods in map interface
❖ Syntax :
✓ Create new non static class:
✓ Create instance of non static class: there are 2 way to access create non static
member class:
➢ 1st way:
▪ A special form of the new operator is used to instantiate a non-
static member class:
▪ Example:
➢ 2nd way:
▪ Create method to create new instance for non static member class
like this:
❖ Non static member class cannot have static members. If you do that you have compiler
error. the reason for this is static members should be accessible without an object but we
know that to create inner class object we first need to create outer class object
❖
❖ Access:
✓ From the enclosing class we can access the inner classes method using the inner
object reference
✓ How inner class can access outer member: Here go method is accessed from inner
class:
➢ If go is not exist in the inner class then it will invoke the go method in the
outer class
➢ This in inner class always reference to inner class members: for example if
go in outer class only and we invoke this.go() then we have compiler error
➢ If you want to explicitly access method from outer class then we can use
<enclosing class name>.this.<method name> (use that if inner and outer
have same name method)
❖ With anonymous class, we are both declaring and instantiating at the point of use and we
can to anywhere but usually it used as method argument
❖ Any local variables access from the enclosing method should be final. However from
JDK 8, it is possible to access the non-final local variable of enclosing block in local
inner class.
Note that in order to be able to use local variables, they must be effectively final
that’s means we cannot change value of local variable in nested class
❖ Common use of anonymous class:
✓ Is for creating function objects: the comparator implementation we just sow was
an example for function object
✓ Function object has 2 property associated with it:
➢ Its methods operate on other objects: that is method parameters are other
objects
➢ It export only one method
✓ If anonymous interface is interface so we refer to it as functional interface
✓ Functional interface however it does have more than one method (it has one
abstract method)
❖ Item 21: use function objects to represent strategies as in strategy pattern
✓ For example compare method has defined strategy of comparing via length of
input strings
✓ We can use other anonymous classes to define other strategies
❖ Syntax: to create anonymous class we can just extend existing class or implement
existing interface only
✓ Extends class:
➢ When we instantiate an anonymous class from an existent one, we use the
following syntax:
➢ Example:
➢ Example:
❖ Anonymous class can have access to the enclosing class if and only if the anonymous
class in non static context. Static context means
✓ It declared inside static method
❖ It cannot have named constructor. But it can use instance initialize to initialize any
variables
❖ Anonymous classes cannot have any static members except for those that are constant.
❖ Limitations:
✓ Cannot inherit from multiple types that we cannot implement multiple interfaces
or extend class and implement interface at same time
✓ Client use anonymous object can only invoke members that are inherited from it
super type that is impossible to invoke any members that are defined only in
anonymous class
✓ It can be instantiated only at the point of the declaration
✓ It cannot be used with instance of tests or anywhere class name is required
✓ From within static member class, we can only access static members of enclosing
class
❖ Static member class is just an ordinary class but declared inside another class
✓ Can include static and instance members
✓ It can make as non instantiable by using private constructor
❖ Common uses:
✓ To represent private component of enclosing object: like Node class in hash map
✓ Represent strategies
✓ Public helper class
❖ But with nested classes, we can shadow local variables like this example
3. Enums
❖ Lets consider class Gender which is constant exporting class and its defining 2 groups of
constants
This kind of pattern that exports only in constants is refer to as int enum pattern
Before java 5, its standard pattern for exporting constants
But it has several deficiencies
✓ Lake of type safety: for instance
▪ Let’s consider this class itself
▪ Let’s say that there is also method which is expecting one field as
input
▪ But client by mistake might pass other field as input
So type safety is lost and it may result some serious error
✓ Code is brittle: these constants are compile time constants So wherever
they are used in client code their values get copied but if any of these
values get changed here then they will not be reflected in client code
unless client code is recompiled
✓ There is no namespace protection: If you want to print name of particular
constant then that would not easy to do
✓ If want to iterate over constants of particular group then it may not be easy
possible
➔ To resolve this problems java designers have better design like this example:
The only problem with this design is that writing such constant exporting class is
cumbersome. Its looks complicated
❖ So language designers wanted to make it simpler. so in java 5, they come with enums
which have simpler representation
❖ So we can represent our example in this way which is much readable
But after compilation, this enum would be translated into regular class. Into byte code
we just have this
✓ in this class, each genre constant have its own value (own age)
✓ for that reason we have constructor for initializing the variable
✓ and each enum constant passes the corresponding value for initializing the
variable (value passes entre parentheses when define constants
✓ It has method for return value of state (in this case for value of age to read).
▪ If we invoke this method enum constant it would return the value of the
state
The enum constants must be the first things to be defined in the enum
❖ Enums can define static members explicitly (static states and behaviors).
✓ to access nested enum constant like HORROR in our example you would do
Book.BookGenre.HORROR
(<enclosing class name>.<nested enum class>.<constant>)
❖ Difference between static member class and nested enum:
✓ Static member class is instantiable
✓ Nested enum is not instantiable
❖ An enum can be nested with within another enum and that enclosing enum can be nested
enum too or top level enum too
❖ Static member class can also have nested enum
Inner class cannot have nested enum as nested enums are implicitly static
Limitation: the limitation with using this way is if we add new enum constant
then we may also have remember to add case block in switch statement
✓ Constant specific methods:
▪ It’s interesting as you can see that each constant is associated with body
▪ This body is refer to as constant specific class body
▪ Specific class body can have
o variables
o methods (are referred to as constant specific method
implementations)
▪ To force developer to add constant specific class body to each constant,
we can add abstract method to enum class
▪ Any variable declare in the enum and it is access within constant specific
body should have access level at least default (not private)
For each constant specific class body definition, the compiler creates an anonymous
class that extends the enum type
If we have enum constants with constants specific class body then the enum type will
no longer be final
4. Concurrency (Multi-threading)
❖ Multithreading is nothing but performing multiple activities at the same time
❖ Many examples for usage of multithreading :
✓ In Smartphone applications updating in background
✓ Web browser where we see the pages and within this pages we have regular
content and images and images keep getting downloading concurrently when
network is very slow
✓ Web sites displaying advertisements
✓ Web crawlers which search engines like Google use
✓ Federated search is an information retrieval technology that allows the
simultaneous search of multiple searchable resources.[citation needed] A user
makes a single query request which is distributed to the search engines, databases
or other query engines participating in the federation. The federated search then
aggregates the results that are received from the search engines for presentation to
the user. Federated search can be used to integrate disparate information resources
within a single large organization ("enterprise") or for the entire web.
❖ Motivation to see why multithreading is needed in the first place:
✓ We know sequential programming where the program is executed one step at time
and most problems can be solved using just sequential programming
✓ However certain tasks like read operations, input output my block until detail
available
✓ Blocking halts other tasks thus wasting CPU time
The solution is concurrent programming which allow you to continue execution
even if task is blocked
4.1. Threads
4.1.1. Introduction
❖ We know when operating system run single program which used all the expensive scare
system resources and that was very inefficient
❖ Operating system then evolve to allow multiple processes to run concurrently
the process is nothing but a running program that is a program instance
❖ each process gets its own resources such is memory file handles … just like the way our
JVM gets its own memory from the underling operating system
❖ an concurrency is achieved through multitasking which is nothing but simply switching
the CPO from one process to another process
multitasking does not imply parallelism a CPO is being switch from one to
another that is at any given instance of time CPO still executing instructions from
single process
❖ however switching having so fast that it give some us an illusion of parallelism which is
possible only on multi process system
4.1.2. Threads
❖ Thread is essentially a single sequential flow of control within process that is statement
within thread are executed sequentially
❖ An thread is part of process and each thread is basically light weight process
❖ An process can have multiple threads
❖ Those threads share the resources that process allocated like the memory and file handles
but each thread has its own PC own stack and local variables.
❖ Threads benefits:
✓ Exploiting multiple processors: that is the threads you creates can run on multiple
processors thus achieving parallelism
✓ Allow loosely couple designs
✓ Better throughput even in single CPU machines when blocking tasks are involved
❖ Threads types: there are 2 types of threads
✓ Daemon thread: is background thread useful for tasks such as garbage collection
✓ Non daemon thread:
▪ Creates within the application that is these are the threads which are
programs create
▪ Main thread: when start our program JVM also creates thread to run the
main method
▪ JVM will not terminate if there is at least one non daemon thread which is
running
❖ Threads analogy:
✓ Step 3: Start the thread: simply invoke the start method on the thread instance
For this new call stack will be created for this thread and the run method and the
run method will be pushed on this stack
❖ Thread Scheduler:
✓ which is responsible for moving the thread from runnable state to running state
✓ once the thread is in running state its call stack would be active and the method on
the top of the stack will be executed
✓ If it’s the run method then run method would be executed.
✓ So it’s the component doing the switching between the threads
✓ There are other state called blocked and there are few reasons why thread can get
to this state and one of them as you is due to blocking during input output
operation like read
✓ Thread can get to block state from only running state and from block state to
runnable state
Thread scheduler makes all decisions about who runs who doesn’t run and
how long they’re run
There is no guarantee on how thread scheduler behaviors
❖ There are many ways to launch thread:
✓ 1st way: Create separate class implement Runnable interface
✓ 2nd way: Thread class itself implement Runnable interface we can do that
Its prefer to use 1st approach because from good object oriented design standpoint if
there are different activities then will be represented by different classes (loosely
couple) and Task/Thread are 2 different activities
❖ To put the thread sleep you can use this method from Thread class like this:
▪ by this static method thread can get access to its own object (to current
thread object)
▪ its static method from Thread class
▪ with that will give reference to the current thread
▪ output of this method is:
▪ here we are saying that main thread suspended until t2 complete its
execution
▪ which mean the executor thread (thread who launch t2 thread) suspended
until invoker thread (t2) complete its execution
▪ Waits for this thread to die.
✓ Let’s consider 2 users ‘John’ and ‘Anita’ and they are married coupe.
✓ They have join bank account and they have balance of only hundred dollars
✓ 2 users are presented by threads and there is task called bank account
✓ Bank account has instance variable called balance and one instance method called
make with dollars which is invoke when user is making with dollars
✓ Implementation of making with dollars method:
✓ When users access banking application then bank account object will be created
for that users account and will passed as input the thread that represent this user
✓ If john and Anita happened to join application in the same time then since they
represent the same account only single bank account object will be created for
them and will be passed as input to that 2 threads
Problem: Let’s consider that john and Anita want to withdraw 75 dollars at the same
time
Bank account object was not thread safe because bank account has state that is the
instance variable balance is mutable
Bank account object was been shared between threads which will access method that
can change the mutable state.
The process of changing the state was not property managed due to bank account was
not thread safe.
When we say properly managed means is they was particular concurrency has that
race condition
❖ The type of race condition is called as check then act which is very common type of race
condition
❖ It called check then act as they first making check if there is enough balance and only
then we are performing some action which is to compute the new balance
❖ the solution is that make with drawal method should be made to run as one single atomic
unit that is once the first thread allow to finish before any other thread can invoke this
method.
This behavior is refer to as mutual exclusion: only once thread can enter the
method at once time
❖ Non thread safe object means an incorrect program which due to data corruption
❖ 2nd example for race condition:
✓ Example:
Synchronization means not only just mutual exclusion but also reliable
communication between threads
✓ Always use the same lock when guarding the same shared mutable variable.
Because when use different locks you can lost concurrency system between
thread.
When john’s thread access make with drawal method then Anita’s thread
cannot access get balance until john’s thread terminate their process
✓ The happens before relationship is achieved through synchronization and this
notion of happens before is part of java’s memory model and JVM implement
java memory model
✓ When we see synchronized keyword than it known that there is need for inter
thread coordination and for this it insert special instruction called memory
barriers which would install the underlying architecture to any necessary
memory coordination between the cache and the shared memory
❖ Happens-before defines a partial ordering on all actions within the program. To guarantee
that the thread executing action Y can see the results of action X (whether or not X and Y
occur in different threads), there must be a happens-before relationship between X and Y.
In the absence of a happens-before ordering between two operations, the JVM is free to
reorder them as it wants
Happens before ordering (rules): Happens-before relationship is a guarantee that
action performed by one thread is visible to another action in different thread.
✓ Single thread rule: Each action in a single thread happens-before every action
in that thread that comes later in the program order.
✓ Monitor lock rule: releasing lock happens before every subsequent acquisition
of that same lock (in own example of make with drawal invoked first then
john’s thread execute method releases the lock which is then acquired by
Anita’s thread in order to get balance
✓ Volatile variable: volatile is keyword that can be used when declaring variable
and the A write to a volatile field happens-before every subsequent read of that
same field. Writes and reads of volatile fields have similar memory
consistency effects as entering and exiting monitors (synchronized block
around reads and writes), but without actually acquiring monitors/locks
✓ Interrupt operation: its method and can be invoked on thread to tell that thread
that is should stop what it’s doing and do something else. Generally it’s
invoked on thread as means to terminate the thread
✓ Object finalize operation: (it invoked by garbage collector when it detect that
there are no more references to the object.) The end of the constructor of an
object happens before the start of the finalize of that object
✓ Transitivity: if action A happens before action B and if action B happens
before action C then action A happens before Action C.
✓ Goal of this is to stop the threads: from the main thread we want to stop the
second thread
✓ There are 2 threads
• One is the main thread
• Other is shown in grey box where we are used anonymous class to
implement the task
✓ We use shared mutable variables declared as volatile and with default value false
✓ Second thread has loop and within loop we are printing some text until stop is set
to true
✓ After second main thread set stop to true so the thread would terminate
✓ If stop variable is not declared as volatile then there is not guarantee that the
second thread will ever get to see the updated value of stop and it may infinitely
loop
Volatile keyword is establishing it happens before ordering and is allowing the 2
threads to coordinate effectively
The same example but with synchronized keyword:
When we use volatile we have memory visibility but we would still have the race
condition when 2 threads access one method at same time.
Synchronization do both it do memory visibility and race condition.
Basically locking that synchronization can guarantee but memory visibility and
mutual exclusion while volatile variable can only guaranty visibility
Use volatile variable: If there is single thread that is writing to shared variable and
other threads read the value of that variable then there is no question of race
condition. Also when we have multi threads writing shared variable same value (like
stop example all threads set to true).
Use synchronization: if there is race condition then we cannot use volatile and we
need to use synchronized also with synchronization we have benefit of memory
visibility.
❖ More on memory semantics:
✓ All actions that precede either write to volatile field or release of lock are visible
to all actions that follow a “subsequent” read of the same volatile variable or
acquisition of same lock.
✓ Let’s say we have thread A and within this thread we have some actions and those
actions either write to volatile field or release of lock
✓ And we have thread B which read from same volatile field or acquires same lock
that was released earlier
✓ With that all the earlier actions that we sow in the cloud will be visible to thread B
also
4.6. Atomic Variables
❖
5.1. Lambdas
❖ Lambda is essentially a function which can be passed around. It’s not associated with any
class and it’s simply a function by itself
❖ It enable in writing faster more compact and cleaner code
❖ Before lambda, anonymous class are used to perform similar tasks of passing around
functionality
❖ Lambda is exactly:
✓ Anonymous function
✓ Its compact way of defining function which can be passed around
✓ Useful when we want to passed some functionality and it helps in doing it in very
compact way
❖ Lambda expression syntax:
The compiler infers the type by type argument that is also specified in
instance creation expression
➢ 2nd simplification: if body has single statement then we can have
something like this (braces, semi colon and ; can be omitted)
✓ If you are creating functional interface then you should also uses this annotation
✓ That way compiler ensure that this interface has only single abstract method
✓ That way if you want to add more than one abstract method you have compiler
error
➢ You can refer to static method defined in the class. Following is the syntax
and example which describe the process of referring static method in Java.
➢ Syntax
➢ Example
➢ Example:
➢ Like static methods, you can refer instance methods also. In the following
example, we are describing the process of referring the instance method.
➢ Syntax
➢ Example
✓ Reference to a constructor:
➢ In this case, we have a lambda expression like the following:
➢ You can refer a constructor by using the new keyword. Here, we are
referring constructor with the help of functional interface
➢ Syntax
➢ Example
5.3. Streams
❖ Stream is consider as one of the best use cases of
✓ Lambdas expressions
✓ Method references
✓ Standard functional interfaces
❖ It’s an API and its introduced as part of new package called “java.util.stream”
❖ Stream is an interface and it has many methods and many of its methods use standard
functional interfaces as method parameter types
❖ Its al about performing SQL operations on collections so we can perform some complex
operations on collections which were not possible earlier before java 8
❖ Problem: So we have database and we have SQL queries which helps us to manipulate
data in the databases and we perform all kinds of complex operations like:
✓ Filtering using where class
✓ Grouping data
✓ Sorting some data
✓ Summary operations like count, sum and average(avg)
❖ Before java 8:
✓ We can:
➢ Add something to collection
➢ Get something from collection
➢ Search
➢
✓ But we cannot do any of this:
➢ Filtering
➢ Grouping
➢ Sorting (collection.sort external sorting)
➢ Sum and avg
✓ Limitations: To do these operations,
➢ Should get some custom code and writing such custom code is not
readable
➢ It’s not easily parallelizable
❖ To address that, java 8 has to introduce stream API and with that we can do all of these
operations
❖ Example:
In java 8, it has introduced new method called stream in Collection interface which
return instance of stream interface and with that you can do any operation to such
collection
If we replace stream method by parallel Stream, then the entire operations is
parallelized like this example so JVM would be able to leverage the different course
in the system and it will be able to parallelize the computation and make it much
more efficient
✓ Streams are lazy because intermediate operations are not evaluated until terminal
operation is invoked
✓ Each intermediate operation creates a new stream, stores the provided
operation/function and return the new stream.
✓ The pipeline accumulates these newly created streams.
✓ The time when terminal operation is called, traversal of streams begins and the
associated function is performed one by one.
✓ Parallel streams don't evaluate streams 'one by one' (at terminal point). The
operations are rather performed simultaneously, depending on the available cores.
JVM for each method is an eager operation so only when JVM is going to execute
for each method and at that instance it’s going to execute lazy methods
✓ Example lazy evaluation in sequential stream
✓ Example lazy evaluation in parallel stream
➢ Used to return only distinct stream elements. If there are duplicated object
then this function will remove it
➢ it remove duplicate
➢ it used equal method and invoke it on each of stream elements
➢ stream element should have equal and hash methods
✓ limit function:
➢ it has input long and it return top parameter elements from stream
➢ it take size which should return as input
➢ after invoke this function, only n elements will be processed and rest of
elements will not be processed
✓ skip function:
➢ It takes predicate and with predicate we are going to pass our criteria
➢ If there is at least one of the stream element is matching criteria in
predicate input
➢ As soon as stream element match this condition then it returns true
otherwise it return false
✓ All match function:
➢ If there are stream of elements, so one of the elements would simply return
that element
➢ The returned element can be second third eight... Element. Its random and
the element returned can be any of them
➢ In non parallel setup typically it would usually return only the first
element but there is non guaranty
✓ Find first function:
✓ it introduced in java 8
✓ is essentially container class which would have either matching element or it will
not have the element
✓ It saying that the value might be present or might not be present.
✓ It used to remove Null pointer exception when stream return null value.
✓ If you would check if optional class contain value use is Present method
✓ If you want to get value use get method
✓ You can use if present method if you have method to invoke if optional class have
value like this example:
✓ You can use or else method if you have to return default value
✓ You can use or else get method. It going to take different parameter take supplier.
Even if element was found then parameter function will not be invoked and it
invoked only if element was not found
✓ You can create optional instance of value using static method called of method
like this
✓ Imperative way:
✓ With parallelization:
➢ Syntax:
If you have in some scenarios the parameters with some types then you should
use this version
✓ Example for using this syntax:
➢ It takes 3 parameters
✓ 2 version:
nd
➢ it returns string
➢ it taking single parameter and it is called as collector
➢ Collector is an interface in util package
▪ Has certain methods which would return supplier accumulator and
combiner to perform mutable reduction
▪ Has couple of more methods
➢ Collectors class is essentially helper class and it’s helping in performing
some predefining reductions like to list, to set , joining …
➢ Joining is predefining reduction about concatenating strings
❖ Collector interface presentation:
✓ Is reduction operator and it helps in performing mutable accumulation if stream
into container
✓ It has many methods like:
➢ Supplier method: help in creating the container which we are suppose to
return. It return instance if supplier functional interface
➢ Accumulator method: accumulates stream elements into the container
➢ Combiner method: combine two result container which would the output
of 2 different segments in parallel streams
➢ Finisher method: optionally transform container object into something else
✓ Predefined collectors:
❖ For computers, kind of interpretation of time is represented by the model time as single
large number representing a point on continuous timeline
❖ The origin of this timeline called epoch has be arbitrary set at midnight on January 1st
1970 (same convention used in UNIX referred to as Unix time)
❖ In case of computers epoch is considered as starting point sp time is measure forward and
also backward. So any time is considered as single large number on the timeline line
number of seconds elapsed since epoch time is referred as zero
✓ Let’s consider class called hello and let’s assume that this class been accessed for
the very first time which means that it’s either been run from the command line or
it’s been accessed in some way from some other class (used by class loader)
When class loader has to load this class it searches the class path to see
where we can find this class
Ones it find this class it load corresponding byte code into memory
And after that it generate something called class object which is the output
of the loading step (contain meta information like class name and names
of any of super classes and method names …)
After all that class loader will simply create class object (java.lang.Class)
from memory and it would use it
✓ In that case (accessed for very first time) we need to load this class into memory
in JVM does that
✓ It checks that whether this class is well formed or not? (that is whether it’s
obeying the language rules of java)
It’s done by compiler when .class file is generated
Verification is performed by component called byte verifier
Why is doing one more time: the reason is this class hello. class could
have been downloaded across the network and it could have been compiled by
host compiler whose intention is to perform some malitions actions on the system
on which it’s going to be executed
After check if it’s not perform so it reject this class which mean it’s not
going to executed
✓ If the file is well formed, then it allocates spaces for any of static variables within
this class and it’s also go to initialize those variables with default values
✓ If class access for very first time, by creating an instance of it then all of instance
variables will also be allocated space and initialized with default values
✓ Load any reference classes. This class could be accessing other variables or
methods in other classes or creating instances of other classes. So in this case we
want to load all classes that are being referenced from this class
✓ Initialize variables: earlier we create space for static variables and initialize with
default values so here we going to override those default values with actual user
defined initial value (in initialize blocks)
➔ If we load class, then super class will be loaded before this class will be loaded
➔ If type to loaded is interface then it will be loaded and not initialized and will be
initialized only if one of its static methods are accessed or field initialized via method
✓ Finally the type will be executed
7.1.1. Loading
❖ Here is illustration of class loading process:
✓ Whenever type is accessed be class or interface, the class loader first checks if
corresponding class object is already on the heap.
➢ If it is on the heap it returns the class object
➢ Otherwise it means the type is accessed for the very first time
✓ The class loader tries to locate the corresponding .class file using something
called parent delegation model
➢ If .class is found then class loader loads the corresponding byte codes
and creates class object and returns it and the class will stored on the
heap for future use
➢ If .class file not found the exception called class not found exception is
generated
❖ Parent delegation model is:
✓ Java has multiple class loaders each loading classes from different repositories
✓ Bootstrap class loader (primordial class loader): It loads all core java API
classes (jre/lib/rt)
✓ Extension class loader: which is responsible for loading classes from standard
java extension API’s which is in (jre/lib/ext/*)
✓ Application/system class loader: loads application classes from the class path
➢ In application class loader we have user defined class loader: they are
custom class loaders created by regular developers and they are used to
load classes from non standard user defined sources like encrypted files
databases and so on. They extends abstract class called
java.lang.ClassLoader
❖ First time loading of class when:
✓ New instance are created
✓ Invoking static method
✓ Accessing static fields
➢ Exception compiles time constants. If one class use compile time
constants then they’re copied where they are used (into .class file)
✓ Subclass is loaded
✓ It is run from command line
✓ Via reflection
❖ First time loading of interface when:
✓ Invoking static method (from java 8)
✓ Accessing static fields
✓ Subclass is loaded or sub interface is loaded
✓ Run from command line (java 8)
✓ Reflection
❖ Class object (output of class loading process):
✓ all objects that will created from particular class is always done using class object
of that class
✓ have meta-information’s:
✓ classes that can be loaded are any of these types
➢ class
➢ interface
➢ primitives
➢ void
➢ arrays: all arrays of same dimensions and same type have the same
class object (length of array haven’t any role here)
7.1.2. Linking
❖ Linking is the most complicated of the 3 stages of the lifetime of type and it includes 3
steps:
✓ Verification
✓ Preparation
✓ Resolution (optional)
❖ Verification step:
✓ Verifies the loaded class is not malformed that is it conforms to the java language
rules
✓ This is needed as the class file might have been loaded from across network or it
could be user defined class from local file system
✓ In either case JVM does not trust those classes as they come from less trustworthy
resources they could have been generated from hostile compiler whose intention
is to perform some malicious actions
✓ Byte code verification is done by component byte code verifier.
➢ Once code is successfully verified by byte code verifier only then code
is considered safe to be run by JVM and it would allowed it’s execution engine to
perform at optimum level as it doesn’t have to perform any further security checks
➢ If verifier has problem it rejects mal formed class and throws exception
✓ Some verifications checks
➢ Final class are not sub classed
➢ Final method are not overridden
➢ No illegal method overloading
➢ Byte code integrity statement like if condition does not send control
beyond method boundary
❖ Preparation step:
✓ Allocate space for static fields and initialize them with default value
✓ If there isn’t enough memory then OutOfMemoryError will be generated
✓ If class loaded because instance of it is created then space will be allocated with
for instance fields also and they also be initialized with default values
Static fields will be initialized before instance field are initialized
❖ Resolution step (optional step):
✓ Resolves symbolic references (reference fields and methods from other classes)
and load them so that current class can use them
✓ Symbolic references
➢ Logical references
➢ Are stored in constant pool(area of .class file) constant pool includes
compile time constants and string literals too
➢ At runtime, referenced class are loaded into memory after their
corresponding symbolic references within current class will be replaced
with direct references to their actual location in the memory
7.2. Reflection
❖ Reflection allows programs to do 2 things:
✓ It allows programs to introspect known or unknown code. For example it
allows us to you what methods fields and constructors are defined in particular
class or an object without even known their names at compile time
You can get all this meta-information directly at runtime
Al you need is class name as string or object reference or even name of
interface and you can get all these meta-information
✓ Allows affecting runtime behavior too. For example if you just know the class
name at runtime you will be able to load the class create instance of the class
and even invoke certain methods on that instance and even set or get value of
fields of that instance
❖ Reflection use cases:
✓ IDE like eclipse use reflection to offer that class browsing capability
✓ Processing annotations (meta data added to source code): for example ORM
framework like hibernate uses reflection to identify members of class that are
annotated
✓ When create dynamic proxies:
➢ For example we have student class with method update profile
➢ Let’s say we want to assume the time it takes to execute this method
and maybe we also want to do same for many of our classes
➢ In such case, we can drop instance of student class in dynamic proxy
and that proxy provide additional logic to measure method execution
time
➢ Client can invoke update profile method on dynamic proxy and the
proxy would intern invoke update method in student class
❖ In last lesson we are know that class object is all about this meta-information. Sp we are
going to use class object here in reflection.
✓ It’s not just JVM class loader that make use of class object but even we
developers can make use of class object while using reflection
✓ The entry point of reflection is by getting reference to the class object
✓ Reflection is not possible without access to class object
✓ Reflection is not constrained to just this class called Class but class from
java.lang.reflect package are also part of reflection
❖ How we can access class object:
✓ There are 3 ways to access class object
➢ Using object reference:
When invoke get class to set interface we get class for hash set class
Example for using
➢ Using class.forName:
✓ There are field called TYPES in every field for primitives and void and it
returns class object for corresponding primitive
➢ Boxed primitives have TYPE field
➔ .class is preferred
➢ Class loader check if class object for particular class is already on the heap
➢ If it’s not there it would then create class object on the heap and the
corresponding class data in method area
➢ JVM would class new instance of that class and would stored on the heap
➢ If new object of this class be created the only object would be created and
store on the heap
❖ Method area: it contain class data which include
✓ Meta information of the type like fully quailed name of type, super class super
interface, is class or interface, info. Type modifiers like abstract final and public
class object uses class data stored in method area to access to these
information’s
✓ Reference to class object.
✓ Field info like static and instance variables: it include field name type and any
associated modifiers like static …
If field is instance variable then it value stored on the heap
If it is static variable then it’s value stored on method area
If it is object then it stored on heap but its reference stored in method area in
case of static variables
✓ Runtime constant pool: its runtime version of constant pool. It includes literals or
symbolic references
✓ Method info like method name, return type, num and type of parameters,
modifiers method byte code
✓ Method table: array of references to instance methods (not static methods) it used
during method invocation process. Each reference pointer to method byte code
stored on method area
➢ Assigning null:
➢ You shouldn’t go about nulling every object reference and that would be
unclean code
➢ But you should use nulling when you’re your program is managing its
own memory like in the case of stack example here
✓ You can use performing monitoring tools to remove any memory leaks in you
program
➢ JProfiler: This is a very useful tool. For couple of my projects, it helped
me in identifying code that was pretty slow. It will help you identify
performance at a method level (e.g., how much time a method is taking).
Subsequently, I was to use better algorithms to speed up the process. You
can try out their trial version
➢ Plumbr: they claim that they are very good at identifying memory leaks.
They have really good resources on their site. You should be able to use
their trial version too
7.5. Stack
❖ Stock store all information about method that are getting invoked and executed (methods
that executed now and not that should be executed or finished of its execution)
❖ It also store all information about local variables in each of executing methods
❖ It’s basically LIFO data structure
❖ Like heap and method area, JVM creates stack for each newly created thread
✓ When method is invoked, an entity called stack frame representing that method
is created and pushed on the top of the stack
✓ If this method invokes another method, then new stack frame will be created
for that new method and that stack frame will also be pushed on the top of the
stack
✓ Frame is pop of the stack when the method invocation completes either
normally or when through some kind of error (in this step, all local variable for
this popped method are considered like dead objects and trailed with garbage
collection)
✓ If local variable is an object reference, then that variable is stored in its own
stack frame well the object is referencing will be stored on the heap