0% found this document useful (0 votes)
9 views115 pages

CS8392 Oops Unit 4

The document covers multithreading and generic programming, detailing concepts such as thread life cycle, thread creation, synchronization, and inter-thread communication. It explains multiprogramming, multiprocessing, and multitasking, along with the importance of thread priority and daemon threads. Additionally, it discusses Java's garbage collection, synchronization mechanisms, and inter-thread communication methods like wait(), notify(), and notifyAll().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views115 pages

CS8392 Oops Unit 4

The document covers multithreading and generic programming, detailing concepts such as thread life cycle, thread creation, synchronization, and inter-thread communication. It explains multiprogramming, multiprocessing, and multitasking, along with the importance of thread priority and daemon threads. Additionally, it discusses Java's garbage collection, synchronization mechanisms, and inter-thread communication methods like wait(), notify(), and notifyAll().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

UNIT IV

MULTITHREADING AND GENERIC PROGRAMMING

• Differences between multi-threading and


multitasking, thread life cycle, creating
threads, synchronizing threads, Inter-thread
communication, daemon threads, thread
groups. Generic Programming – Generic
classes – generic methods – Bounded Types –
Restrictions and Limitations.
Multiprogramming
• "The concurrent residency of more than one program
in the main memory is referred as multiprogramming."
• Since multiple programs are resident in the memory, as
soon as the currently executing program finishes its
execution, the next program is dispatched for its
consumption.
• Also if the currently executing program asks for input
output resources then meanwhile another program is
dispatched to the CPU for execution.
• The main objective of multiprogramming is:
• Maximum CPU utilization.
• Efficient management of the main memory.
• Multiprogramming can be virtually shown as:
Multiprocessing
• When one system is connected to more than one
processor which collectively work for the
completion of the task, it is called as
multiprocessing systems.
• Multiprocessing systems can be divided in two
types:
– Symmetric Multiprocessing: The operating system
here resides on one processor and the other
processors run user's programs.
– Asymmetric Multiprocessing: The OS runs on any
available processor or all the processor
simultaneously run the user program.
Multiprocessing systems can be virtually represented as:
Multithreading
• "Multithreading is a conceptual programming
paradigm where a process is divided into a
number of sub-processes called as threads.
Each thread is independent and has its own
path of execution with enabled inter thread
communication."
• "Thread is the path followed while executing a
program. Each thread has its own program
counter, stack and register."
• A thread is a light weight process.
• It can be virtually represented as:
Multitasking
• Earlier when computers were invented, a user was
allowed to submit only job or task at a time. But later
with availability of high-speed processor, one can
submit more than one task.
• So the capability of OS to accept more the one task per
user is termed as multitasking.
• Multiple jobs are executed by the CPU simultaneously
by switching between them.
• The various job can be accepted from same user or
different users. There are 2 types of multitasking
systems:
• Single User Multitasking
• Multi User multitasking
• It can be virtually represented as:
Life cycle of a Thread (Thread States)
• A thread can be in one of the five states.
According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-
runnable and terminated. There is no running
state.
• But for better understanding the threads, we
are explaining it in the 5 states.
• The life cycle of the thread in java is controlled
by JVM.
The java thread states are as follows:

• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
1) New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.

2) Runnable
The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.

3) Running
The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not
eligible to run.

5) Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread

There are two ways to create a thread:


• By extending Thread class
• By implementing Runnable interface.
Thread class
• Thread class provide constructors and methods
to create and perform operations on a thread.
• Thread class extends Object class and
implements Runnable interface.
Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
Commonly used methods of Thread class
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
• public void sleep(long miliseconds): Causes the currently executing thread
to sleep (temporarily cease execution) for the specified number of
milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently
executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended
thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user
thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been
interrupted.
Runnable interface
• The Runnable interface should be
implemented by any class whose instances are
intended to be executed by a thread.
Runnable interface have only one method
named run().
• public void run(): is used to perform action for
a thread.
Starting a thread
• start() method of Thread class is used to start
a newly created thread.
• It performs following tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the
Runnable state.
• When the thread gets a chance to execute, its
target run() method will run.
• If you are not extending the Thread class,your
class object would not be treated as a thread
object.
• So you need to explicitly create Thread class
object.
• We are passing the object of your class that
implements Runnable so that your class run()
method may execute.
Sleep method in java
• The sleep() method of Thread class is used to
sleep a thread for the specified amount of time.

Syntax of sleep() method in java


The Thread class provides two methods for sleeping
a thread:

• public static void sleep(long miliseconds)throws


InterruptedException
• public static void sleep(long miliseconds, int
nanos)throws InterruptedException
What if we call run() method directly
instead start() method?

• Each thread starts in a separate call stack.


• Invoking the run() method from main thread,
the run() method goes onto the current call
stack rather than at the beginning of a new
call stack.
The join() method
• The join() method waits for a thread to die. In
other words, it causes the currently running
threads to stop executing until the thread it
joins with completes its task.
Syntax:
• public void join()throws InterruptedException
• public void join(long milliseconds)throws
InterruptedException
Priority of a Thread (Thread Priority)
• Each thread have a priority.
• Priorities are represented by a number between 1 and 10.
• In most cases, thread schedular schedules the threads
according to their priority (known as preemptive scheduling).
• But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY).
• The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
Daemon Thread in Java
• Daemon thread in java is a service provider thread that
provides services to the user thread.
• Its life depend on the mercy of user threads i.e. when all
the user threads dies, JVM terminates this thread
automatically.
• There are many java daemon threads running automatically
e.g. gc, finalizer etc.

• You can see all the detail by typing the jconsole in the
command prompt.
• The jconsole tool provides information about the loaded
classes, memory usage, running threads etc.
Points to remember for Daemon
Thread in Java

• It provides services to user threads for


background supporting tasks.
• It has no role in life than to serve user
threads.
• Its life depends on user threads.
• It is a low priority thread.
• Why JVM terminates the daemon thread if
there is no user thread?
• The sole purpose of the daemon thread is that
it provides services to user thread for
background supporting task.
• If there is no user thread, why should JVM
keep running this thread.
• That is why JVM terminates the daemon
thread if there is no user thread.
ThreadGroup in Java
• Java provides a convenient way to group multiple threads in a
single object.
• In such way, we can suspend, resume or interrupt group of
threads by a single method call.
• Java thread group is implemented by java.lang.ThreadGroup
class.
• A ThreadGroup represents a set of threads. A thread group can
also include the other thread group.
• The thread group creates a tree in which every thread group
except the initial thread group has a parent.
• A thread is allowed to access information about its own thread
group, but it cannot access the information about its thread
group's parent thread group or any other thread groups.
Java Garbage Collection
• In java, garbage means unreferenced objects.

• Garbage Collection is process of reclaiming the


runtime unused memory automatically.
• In other words, it is a way to destroy the unused
objects.
• To do so, we were using free() function in C language
and delete() in C++.
• But, in java it is performed automatically. So, java
provides better memory management.
Advantage of Garbage Collection
• It makes java memory efficient because garbage
collector removes the unreferenced objects from
heap memory.
• It is automatically done by the garbage
collector(a part of JVM) so we don't need to
make extra efforts.

How can an object be unreferenced?


There are many ways:
• By nulling the reference
• By assigning a reference to another
• By anonymous object etc.
Java Runtime class
• Java Runtime class is used to interact with java
runtime environment.
• Java Runtime class provides methods to execute
a process, invoke GC, get total and free memory
etc.
• There is only one instance of java.lang.Runtime
class is available for one java application.
• The Runtime.getRuntime() method returns the
singleton instance of Runtime class.
Synchronization in Java
• Synchronization in java is the capability to control
the access of multiple threads to any shared
resource.
• Java Synchronization is better option where we
want to allow only one thread to access the
shared resource.
• Why use Synchronization
• The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
• There are two types of thread synchronization
mutual exclusive and inter-thread
communication.

• Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
• Cooperation (Inter-thread communication in java)
Mutual Exclusive
• Mutual Exclusive helps keep threads from
interfering with one another while sharing data.

This can be done by three ways in java:

 by synchronized method
 by synchronized block
 by static synchronization
Concept of Lock in Java
• Synchronization is built around an internal entity
known as the lock or monitor.
• Every object has an lock associated with it. By
convention, a thread that needs consistent access
to an object's fields has to acquire the object's lock
before accessing them, and then release the lock
when it's done with them.

• From Java 5 the package java.util.concurrent.locks


contains several lock implementations.
Java synchronized method
• If you declare any method as synchronized, it is
known as synchronized method.

• Synchronized method is used to lock an object for


any shared resource.

• When a thread invokes a synchronized method, it


automatically acquires the lock for that object
and releases it when the thread completes its
task.
Synchronized Block in Java
• Synchronized block can be used to perform
synchronization on any specific resource of the
method.
• Suppose you have 50 lines of code in your
method, but you want to synchronize only 5 lines,
you can use synchronized block.
• If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.
SIMPLE EXAMPLE OF SYNCHRONIZED BLOCK.
Static Synchronization
• If you make any static method as
synchronized, the lock will be on the class not
on object.
Problem without static synchronization
• Suppose there are two objects of a shared class(e.g.
Table) named object1 and object2.
• In case of synchronized method and synchronized
block there cannot be interference between t1 and
t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock.
• But there can be interference between t1 and t3 or
t2 and t4 because t1 acquires another lock and t3
acquires another lock.
• I want no interference between t1 and t3 or t2 and
t4.
• Static synchronization solves this problem.
Example of static synchronization
Deadlock in java
• Deadlock in java is a part of multithreading.
Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by
another thread and second thread is waiting for
an object lock that is acquired by first thread.
• Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Inter-thread communication in Java
• Inter-thread communication or Co-operation is all
about allowing synchronized threads to communicate
with each other.
• Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter
(or lock) in the same critical section to be executed.
• It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
1) wait() method
• Causes current thread to release the lock and
wait until either another thread invokes the
notify() method or the notifyAll() method for this
object, or a specified amount of time has
elapsed.
• The current thread must own this object's
monitor, so it must be called from the
synchronized method only otherwise it will throw
exception.
2) notify() method
• Wakes up a single thread that is waiting on this
object's monitor.
• If any threads are waiting on this object, one of
them is chosen to be awakened.
• The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax:
public final void notify()
3) notifyAll() method
• Wakes up all threads that are waiting on this
object's monitor. Syntax:

public final void notifyAll()


Understanding the process of inter-
thread communication
The point to point explanation of the above diagram is
as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait()
method on the object. Otherwise it releases the
lock and exits.
4. If you call notify() or notifyAll() method, thread
moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the
lock and exits the monitor state of the object.
Difference between wait and sleep?
Example of inter thread communication in java
Generics in Java
• The Java Generics programming is introduced in
J2SE 5 to deal with type-safe objects.
• It makes the code stable by detecting the bugs at
compile time.

• Before generics, we can store any type of objects


in the collection, i.e., non-generic. Now generics
force the java programmer to store a specific type
of objects.
Advantage of Java Generics
• There are mainly 3 advantages of generics.
1) Type-safety
• We can hold only a single type of objects in generics.
• It doesn’t allow to store other objects.
• Without Generics, we can store any type of objects.
2) Type casting is not required
There is no need to typecast the object.
3) Compile-Time Checking
It is checked at compile time so problem will not occur at
runtime. The good programming strategy says it is far better
to handle the problem at compile time than runtime.
Example of Generics in Java
Generic class
• A class that can refer to any type is known as a
generic class.
• Here, we are using the T type parameter to create
the generic class of specific type.
• The T type indicates that it can refer to any type
(like String, Integer, and Employee). The type you
specify for the class will be used to store and
retrieve the data.
Type Parameters
• The type parameters naming conventions are
important to learn generics thoroughly.
• The common type parameters are as follows:

 T - Type
 E - Element
 K - Key
 N - Number
 V - Value
Generic Method
• Like the generic class, we can create a generic
method that can accept any type of arguments.
• Here, the scope of arguments is limited to the
method where it is declared.
• It allows static as well as non-static methods.
simple example of java generic method to print array elements.
We are using here E to denote the element.
Wildcard in Java Generics
• The ? (question mark) symbol represents the
wildcard element. It means any type. If we write <?
extends Number>, it means any child class of
Number, e.g., Integer, Float, and double.
• Now we can call the method of Number class
through any child class object.

• We can use a wildcard as a type of a parameter, field,


return type, or local variable.
• However, it is not allowed to use a wildcard as a type
argument for a generic method invocation, a generic
class instance creation, or a supertype.
Upper Bounded Wildcards
• The purpose of upper bounded wildcards is to
decrease the restrictions on a variable.
• It restricts the unknown type to be a specific type or
a subtype of that type.
• It is used by declaring wildcard character ("?")
followed by the extends (in case of, class) or
implements (in case of, interface) keyword, followed
by its upper bound.
Syntax
List<? extends Number>

Here,

 ? is a wildcard character.
 extends, is a keyword.
 Number, is a class present in java.lang package

• Suppose, we want to write the method for the list of Number and
its subtypes (like Integer, Double).
• Using List<? extends Number> is suitable for a list of type Number
or any of its subclasses whereas List<Number> works with the list
of type Number only.
• So, List<? extends Number> is less restrictive than List<Number>.
Example of Upper Bound Wildcard
Output

displaying the sum= 30.0


displaying the sum= 70.0
Unbounded Wildcards
• The unbounded wildcard type represents the list of
an unknown type such as List<?>.
• This approach can be useful in the following
scenarios: -

• When the given method is implemented by using the


functionality provided in the Object class.
• When the generic class contains the methods that
don't depend on the type parameter.
Lower Bounded Wildcards
• The purpose of lower bounded wildcards is to
restrict the unknown type to be a specific type or
a supertype of that type.
• It is used by declaring wildcard character ("?")
followed by the super keyword, followed by its
lower bound.
Syntax
List<? super Integer>
Here,
 ? is a wildcard character.
 super, is a keyword.
 Integer, is a wrapper class.
• Suppose, we want to write the method for the list of
Integer and its supertype (like Number, Object).
• Using List<? super Integer> is suitable for a list of type
Integer or any of its superclasses
whereas List<Integer> works with the list of type
Integer only.
• So, List<? super Integer> is less restrictive
than List<Integer>.
Restrictions on Generics
• To use Java generics effectively, you must consider the
following restrictions:

 Cannot Instantiate Generic Types with Primitive Types


 Cannot Create Instances of Type Parameters
 Cannot Declare Static Fields Whose Types are Type
Parameters
 Cannot Use Casts or instanceof With Parameterized Types
 Cannot Create Arrays of Parameterized Types
 Cannot Create, Catch, or Throw Objects of Parameterized
Types
 Cannot Overload a Method Where the Formal Parameter
Types of Each Overload Erase to the Same Raw Type

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy