0% found this document useful (0 votes)
5 views138 pages

OOP Java - Unit 3

This document covers Exception Handling and Multithreading in Java, focusing on how exceptions interrupt program flow and how they can be handled using try, catch, and finally blocks. It explains the types of exceptions (checked and unchecked), the use of multiple catch clauses, and the throw and throws keywords for managing exceptions. Additionally, it provides examples to illustrate exception handling concepts in Java programming.

Uploaded by

amreen2825
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)
5 views138 pages

OOP Java - Unit 3

This document covers Exception Handling and Multithreading in Java, focusing on how exceptions interrupt program flow and how they can be handled using try, catch, and finally blocks. It explains the types of exceptions (checked and unchecked), the use of multiple catch clauses, and the throw and throws keywords for managing exceptions. Additionally, it provides examples to illustrate exception handling concepts in Java programming.

Uploaded by

amreen2825
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/ 138

Prepared by GSK

OBJECT ORIENTED
PROGRAMMING THROUGH JAVA
UNIT-3

Ch-1. Exception Handling


1 Ch-2. Multithreading
Prepared by GSK
CHAPTER - 1
EXCEPTION HANDLING
2
WHAT IS AN EXCEPTION?
 An Exception is an unwanted event that
interrupts the normal flow of the program.
 When an exception occurs program execution

Prepared by GSK
gets terminated. In such cases we get a system
generated error message.
 The good thing about exceptions is that they can
be handled by programmers also.
 By handling the exceptions we can provide a
meaningful message to the user about the
3
issue rather than a system generated message.
 The problem with the exception is, it terminates
the program and skip rest of the execution
that means if a program have 100 lines of code
and at line 10 an exception occur then

Prepared by GSK
program will terminate immediately by
skipping execution of rest 90 lines of code.

 To handle this problem, we use exception


handling that avoid program termination
and continue the execution.
4
WHY AN EXCEPTION OCCURS?

 There can be several reasons that can cause


a program to throw exception.

Prepared by GSK
 For example:

➢ Opening a non-existing file in your


program

➢ Network connection problem

➢ Invalid input data provided by user etc. 5


Prepared by GSK
6
TYPES OF EXCEPTIONS CONTD..
 In Java, exceptions broadly can be categories into
checked exception and unchecked exception based
on the nature of exception.

Prepared by GSK
Checked Exception:
 The exception that can be predicted at the compile time.
The checked exceptions are generally caused by faults
outside of the code itself like missing resources,
networking errors.
 Example : File that need to be opened is not found,
SQLException etc. These type of exceptions must be
7
checked at compile time.
TYPES OF EXCEPTIONS CONTD..
Unchecked Exception:

 Unchecked exception are ignored at compile time

Prepared by GSK
and checked at runtime. The unchecked exceptions
are generally caused due to bugs such as logic
errors.

 Examples:

❑ ArithmeticException,

❑ NullPointerException, 8

❑ ArrayIndexoutofBound exception.
Prepared by GSK
9
Prepared by GSK
Hierarchy of 10
Exception Classes
UNCAUGHT EXCEPTION
class UncaughtException
{
public static void main(String args[])
{

Prepared by GSK
As we don't have any mechanism for
int a = 0; handling exception in this program,
hence the default handler (JVM) will
int b = 7/a; //exception handle the exception and will print
} the details of the exception on the
terminal.
}

11
HOW TO HANDLE EXCEPTION

 Java provides controls to handle exception in


the program. These controls are:

Prepared by GSK
 try : It is used to enclose the suspected code.
 catch: It acts as exception handler.
 finally: It is used to execute necessary code.
 throw: It throws the exception explicitly.
 throws: It informs for the possible Exception.
12
TRY AND CATCH IN JAVA
 Try and catch both are Java keywords and used
for exception handling.

Prepared by GSK
 The try block is used to enclose the suspected code.
Suspected code is a code that may raise an
exception during program execution.

try
{
int a = 10;
int b = 0
int c = a/b; // exception 13

}
TRY AND CATCH IN JAVA CONTD..

 The catch block also known as handler is used


to handle the exception.

Prepared by GSK
 It handles the exception thrown by the code
enclosed into the try block.
 The catch block must be used after the try
block only.
 We can also use multiple catch block with a
single try block.
14
try
{
int a = 10;
int b = 0

Prepared by GSK
int c = a/b; // exception
}
catch(ArithmeticException e)
{
System.out.println(e);
15

}
//Java program to demonstrate NullPointerException

class NullPointer_Demo
{
public static void main(String args[])
{
try

Prepared by GSK
{
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
} Output: 16

NullPointerException..
NULLPOINTEREXCEPTION

In the previous slide

A String variable a is assigned a null value.

Prepared by GSK
 The program tries to access the first character
of the string using a.charAt(0), which causes a
NullPointerException because a is null.

 The exception is caught in the catch block, and


"NullPointerException.." is printed to the
17
console.
 NullPointerException is a RuntimeException.
In Java, a special null value can be assigned to
an object reference.
 NullPointerException is thrown when program

Prepared by GSK
attempts to use an object reference that has the
null value.
 null is a special value used in Java.
 It is mainly used to indicate that no value is
assigned to a reference variable.
 One application of null is in implementing data
18
structures like linked list and tree
Example: Handling Arithmetic Exception
class Exception Output:
{
Divided by zero
public static void main(String args[])
{ After exception is handled
int a,b,c; Output:
try Divided by zero

Prepared by GSK
{ After exception is handled
a = 0;
b = 10;
c = b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled"); 19
}
}
EXECUTION PROCEDURE
 An exception will thrown by this program as we
are trying to divide a number by zero
inside try block.

Prepared by GSK
 The program control is transferred
outside try block. Thus the line "This line will not
be executed" is never parsed by the compiler.
 The exception thrown is handled in catch block.

 Once the exception is handled, the program control


is continue with the next line in the program i.e
after catch block.
 Thus the line "After exception is handled" is
printed. 20
FINALLY KEYWORD IN JAVA

 The finally keyword used to define a block


that must be executed irrespective of

Prepared by GSK
exception occurrence.
 The basic purpose of finally keyword is to
cleanup resources allocated by try block, such
as closing file, closing database connection,
etc.
 Use of finally block is optional 21
MULTIPLE CATCH CLAUSES
 A try block can be followed by multiple catch blocks.

 It means we can have any number of catch


blocks after a single try block.

Prepared by GSK
 If an exception occurs in the try block, the exception
is passed to the first catch block in the list. If the
exception type matches with the first catch block it
gets caught, if not the exception is passed down to
the next catch block. This continue until the
exception is caught or failed to catch. 22
MULTIPLE CATCH SYNTAX
try
{
// suspected code Note:

Prepared by GSK
}
At a time, only one
catch(Exception1 e)
{ exception is
// handler code processed and only
}
one respective catch
catch(Exception2 e)
{ block is executed.
// handler code
23
}
public class MulCatch
{
public static void main(String[] args)
{ Output:
try ArrayIndexOutOfBounds
{ Exception -->
java.lang.ArrayIndexOut

Prepared by GSK
int a[ ]=new int[10]; OfBoundsException:
System.out.println(a[20]); Index
} 20 out of bounds for
length 10
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception --> "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds 24
Exception --> "+e);
} } }
UNREACHABLE CATCH BLOCK

 While using multiple catch statements, it is


important to remember that sub classes of

Prepared by GSK
class Exception inside catch must come
before any of their super classes otherwise it
will lead to compile time error.

25
class UnreachCatch Program to implement Unreachable Catch block
{
public static void main(String[] args)
{
try Output:
{ Error
int arr[]={1,2};

Prepared by GSK
arr[2]=3/2;
}
catch(Throwable e) //This block handles all Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
} 26
}
NESTED TRY STATEMENT
 try statement can be nested inside another block
of try. Nested try block is used when a part of a block
may cause one error while entire block may cause

Prepared by GSK
another error.

 In case if inner try block does not have a catch handler


for a particular exception then the outer try catch
block is checked for match.

 In nested try catch, the inner try block uses its own
catch block as well as catch block of the outer try, if
27
required.
class ExceptionsEx
{
public static void main(String[] args)
{ Output:
try
divide by zero array
{
int arr[ ]={5,0,1,2};
index out of bound exception
try

Prepared by GSK
{
int x = arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
} 28
}
} Program to implement Nested Try
THROW KEYWORD IN JAVA
 Sometimes we can create Exception object explicitly
and we can hand over to the JVM manually by using
throw keyword.

Prepared by GSK
 The throw keyword is used to throw an exception
instance explicitly from a try block to
corresponding catch block.
 That means it is used to transfer the control from try
block to corresponding catch block.
 The throw keyword must be used inside
29
the try block.
THROW KEYWORD IN JAVA

 When JVM encounters the throw keyword, it stops the


execution of try block and jump to the corresponding

Prepared by GSK
catch block.

 Using throw keyword only one exception can be


thrown.

 Note: In general we can use throw keyword for


customized/User-defined exceptions but not for
predefined exceptions
30
Prepared by GSK
31
Output:
EXAMPLE 1: Exception in thread "main"
java.lang.ArithmeticException: / by
class Test zero
{ at Test.main(Test.java:6)

public static void main(String[] args)

Prepared by GSK
{
System.out.println(10/0);
}

In this case creation of ArithmeticException


object and handover to the jvm will be performed
32
automatically by the main() method.
Output:
EXAMPLE 2: Exception in thread "main"
java.lang.ArithmeticException: / by
class Test zero
{ at Test.main(Test.java:6)

public static void main(String[] args)

Prepared by GSK
{
throw new ArithmeticException("/ by zero");
}

In this case we are creating exception object


explicitly and handover to the JVM manually.
33
The result of Two Example programs are exactly
same
import java.util.Scanner; Output:
public class ThrowEx Enter any two numbers: 20
{ 0
public static void main(String[] args) Problem info: Division by zero
{ is not possible
End of the program
Scanner input = new Scanner(System.in);
int num1, num2, result;
System.out.print("Enter any two numbers: ");

Prepared by GSK
num1 = input.nextInt();
num2 = input.nextInt();
try
{
if(num2 == 0)
throw new ArithmeticException("Division by zero is not possible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: " + ae.getMessage());
} 34
System.out.println("End of the program"); }}
THROWS KEYWORD IN JAVA
 In our program if there is any chance of raising checked
exception then compulsory we should handle either by
try-catch or by throws keyword otherwise the code

Prepared by GSK
won't compile

 The throws keyword specifies the exceptions that a


method can throw to the default handler and does not
handle itself.

 That means when we need a method to throw an


exception automatically, we use throws keyword
35
followed by method declaration
THROWS KEYWORD IN JAVA

 The throws keyword in Java is used to declare


exceptions that can occur during the
execution of a program.

Prepared by GSK
 For any method that can throw exceptions, it is
mandatory to use the throws keyword to list the
exceptions that can be thrown.

 The throws keyword provides information about the


exceptions to the programmer as well as to the
caller of the method (calling method). 36
 "throws" keyword required only checked
exceptions.

 "throws" keyword required only to

Prepared by GSK
convince complier.

37
Output:Enter your name Amit Welcome Amit
import java.io.*; Output:
Enter your name: Ram
public class InputStr
Welcome Ram
{
public static void main(String[ ] args) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bfr = new BufferedReader(isr);
System.out.println("Enter Your Name:");
String str = bfr.readLine();

//Display the charecter


System.out.print("WelCome " + str);
}} 38
 The reason the main method in your program
declares that it throws an IOException is because
the BufferedReader's readLine() method can throw
this exception.

Prepared by GSK
 IOException: This checked exception signals that
an I/O operation (like reading or writing) failed or
was interrupted.
 When you use BufferedReader.readLine(), the
method can encounter I/O errors such as failing to
read from the input stream (e.g., if the stream is
closed or corrupted). 39
Basic The throw keyword The throws keyword is used to
handover our created delegate the responsibility of
exception object to exception handling to the caller
JVM manually. of the method.

Syntax throw Throwable- return_type


instance; method_name(parameter-list)
throws ExceptionClass_list

Prepared by GSK
{
// body of method
}
Followed The throw keyword is The throws keyword is followed
by followed by exception by the list of the exception
object. classes that can occur in the
method.

Number The throw keyword The throws keyword can declare


of can throw a single multiple exception classes
Exception exception instance. separated by a comma. 40
thrown
Throw vs Throws
EXCEPTION HANDLING KEYWORDS
SUMMARY:

 1. try: To maintain risky code.

2. catch: To maintain handling code.

Prepared by GSK

 3. finally: To maintain cleanup code.

 4. throw: To handover our created exception


object to the JVM manually.

 5. throws: To delegate responsibility of exception


handling to the caller method.
41
USER-DEFINED EXCEPTION (CUSTOM )

 We have seen predefined exceptions provided


by the Java platform.

Prepared by GSK
 These predefined exceptions are used to
handle errors occurring in the program.
 But sometimes the programmer wants to
create his own customized exception as per the
requirements of the application which is
called user-defined exception or custom
45
exception.
 Custom exceptions in Java are those exceptions that
are created by a programmer to meet the
specific requirements of the application. That’s
why it is also known as user-defined exception in
Java.

Prepared by GSK
For example:
 1. A banking application, a customer whose age is
lower than 18 years, the program throws a custom
exception indicating “needs to open joint account”.
 2. Voting age in India: If a person’s age entered is less
than 18 years, the program throws “invalid age” as a
46
custom exception.
HOW TO CREATE YOUR OWN USER-DEFINED
EXCEPTION IN JAVA?
 Step 1: User defined exception basically derived
classes of Exception. This is done as:
class OwnException extends Exception

Prepared by GSK
 Step 2: If you do not want to store any
exception details, define a default constructor in
your own exception class. This can be done as
follows:
OwnException( )
{
47

}
 Step 3: If you want to store exception details, define a
parameterized constructor with string as a parameter,
call superclass (Exception) constructor from this, and
store variable “str”. This can be done as follows:

Prepared by GSK
OwnException(String str)

super(str);

/* Call super class exception constructor and store


variable "str" in it. */

} 48
 Step 4: In the last step, we need to create an
object of user-defined exception class and throw it
using throw clause.

Prepared by GSK
OwnException obj = new
OwnException("Exception details");

throw obj;

or,

throw new OwnException("Exception details");


49
Program to implement User-defined Exception

class TooYoungException extends RuntimeException


{
TooYoungException(String s)
{

Prepared by GSK
super(s);
}
}

class TooOldException extends RuntimeException


{
TooOldException(String s)
{
super(s);
50
}
}
class CustomizedException
{
public static void main(String[ ] args)
{
int age=Integer.parseInt(args[0]); //CommandLine Arguements
if(age>60)
{
throw new TooOldException("Your are too old... Not eligible to

Prepared by GSK
register");
}
else if(age<18)
{
throw new TooYoungException(“You are too young… Not eligible to
register.....");
}
else
{
System.out.println("you will get match details soon by e-mail");
} 51
}
}
Output Case 1:

Javac CustomizedException.java
Java CustomizedException 25

you will get match details soon by e-mail

Prepared by GSK
Output Case 2:

Java CustomizedException 15

Exception in thread "main" TooYoungException:


You are too young….Not eligible to register.....

Output Case 3:

Java CustomizedException 70
52
Exception in thread "main" TooOldException:
you are too old... Not eligible to register
Prepared by GSK
CHAPTER – 2
MULTITHREADING
53
Concurrently: two or
more events happen at
the same time, but not
necessarily at the exact
same moment.
Simultaneously: two or
more events happen at

Prepared by GSK
the exact same moment,
with no time lag
between them

Multitasking in an operating system (OS) refers to the ability of the


OS to run multiple tasks concurrently. This improves system
efficiency and user experience by ensuring that various applications
54

can operate at the same time without significant delays.


 What is a Process?

❖ it is a instance of a program that is executing.

❖ It includes the program code and its current

Prepared by GSK
activity.

 What is a Thread?
A thread is a path of execution within a process.

A process can contain multiple threads.


55
PROCESS BASED MULTITASKING
 In process based multitasking two or more
processes can be run concurrently.
In process based multitasking a process is a

Prepared by GSK

smallest unit.
 Process requires its own address space.
 Process to Process communication is expensive. It is
comparatively heavy weight
 Example – We can listen to music and browse
internet at the same time. The processes in this 56

example are the music player and browser.


Prepared by GSK
Process Based Multitasking 57
THREAD BASED MULTITASKING
 It is also called MultiThreading
 In thread based multitasking two or more threads can
be run concurrently.

Prepared by GSK
 In thread based multitasking a thread is the smallest
unit.
 Thread based multitasking requires less overhead.
 Threads share same address space.
 Thread to Thread communication is not expensive.
 It is comparatively light weight.
58

 It has faster data rate multi-tasking.


Prepared by GSK
59
Thread Based Multitasking
WHAT IS MULTITHREADING?
A process can have multiple threads and
the CPU switches among these threads so

Prepared by GSK
frequently making an impression on the user
that all threads are running simultaneously
and this is called multithreading.

60
MORE EXAMPLES FOR MULTITHREADING

 Using a browser we can navigate through the


webpage and at the same time download a

Prepared by GSK
file.
 In this example, navigation is one thread
and downloading is another thread.
 Also in a word-processing application like
MS Word, we can type text in one thread
and spell checker checks for mistakes in 61
another thread.
APPLICATIONS

The main important areas of multithreading are:


 1.To implement multimedia graphics.

Prepared by GSK
 2. To develop animations.
 3. To develop video games etc.
 4. To develop web and application servers
 5. Whether it is process based or Thread based
the main objective of multitasking is to
improve performance of the system by
62
reducing response time.
Prepared by GSK
Note:
At a time one thread is executed only. 63
ADVANTAGE OF MULTITHREADING

 Multithreading reduces the CPU idle


time that increase overall performance of

Prepared by GSK
the system.

 Since thread is lightweight process then it


takes less memory and perform context
switching as well that helps to share the
memory and reduce time of switching
64
between threads.
HOW TO CREATE THREAD ?

 To create a thread, Java provides a


class Thread and an interface Runnable both

Prepared by GSK
are located in java.lang package.

 We can create thread either by extending


Thread class or implementing Runnable
interface.

 Both includes a run method that must be


override to provide thread implementation. 65
THE MAIN THREAD
 When we run any java program, the program begins to
execute its code starting from the main method.

 Therefore, the JVM creates a thread to start executing

Prepared by GSK
the code present in main method. This thread is called
as main thread.

 The main thread is automatically created.

Two important things to know about main thread are,

 It is the thread from which other threads will be


produced.

 It must be always the last thread to finish execution. 66


MULTITHREADING IN JAVA

A thread begins its life inside run() method.

 We create an object of our new class and call

Prepared by GSK
start() method to start the execution of
a thread.

 Start( ) invokes the run( ) method on the


Thread object.

67
Method-1: Creating a thread by using Thread Class

Step-1: Defining a Thread by extending "Thread class":

Prepared by GSK
68
Step-2:Create an instance of MyThread class and call the start
method and Override the run method

class ThreadDemo
{

public static void main(String[ ] args)

Prepared by GSK
{
ThreadDemo
Thread: Main
MyThread t=new MyThread( ); Thread
//Instantiation of a Thread
t.start()
MyThread
t.start( ); //starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
69
}
}}
Note: We can't expect exact output but there are several possible
outputs.

First Run Second Run Third Run

Prepared by GSK
70
Method-2: Creating a thread by using Runnable Interface

STEP-1: DEFINING A THREAD BY IMPLEMENTING


RUNNABLE INTERFACE

Prepared by GSK
71
Step-2: Create an instance of the MyRunnable class and pass it to a
Thread object, then call the start method.
Implement the run method.
class RunnableDemo
{
public static void main(String[] args)

Prepared by GSK
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);
//here r is a Target Runnable
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
72
}
}}
Prepared by GSK
73
Output:
Prepared by GSK
74
Thread States/ Thread Life Cycle

Prepared by GSK
75
New:

 In this phase, the thread is created using

Prepared by GSK
class "Thread class".

 It remains in this state till the


program starts the thread.

 It is also known as born thread.

76
 Runnable:

Prepared by GSK
 In this State, the instance of the thread is
invoked with a start method.

 The thread control is given to scheduler to


finish the execution.

 It depends on the scheduler, whether to run


the thread. 77
 Running:

Prepared by GSK
 When the thread starts executing, then the
state is changed to "running" state.

 The scheduler selects one thread from the


thread pool, and it starts executing in the
application.
78
Waiting:

 This is the state when a thread has to wait.

Prepared by GSK
 As there multiple threads are running in the
application, there is a need for synchronization
between threads.
 Hence, one thread has to wait, till the other
thread gets executed.
 Therefore, this state is referred as waiting state.
79
Dead:

Prepared by GSK
 This is the state when the thread is
terminated.

 The thread is in running state and as soon


as it completed processing it is in "dead
state".
80
SUMMARY OF STATES OF THREAD

 Once we created a Thread object then the Thread


is said to be in new state or born state.

Prepared by GSK
 Once we call start() method then the Thread will
be entered into Runnable state.

 If Thread Scheduler allocates CPU then the


Thread will be entered into running state.

 Once run( ) method completes then the Thread will


entered into dead state. 81
JAVA THREAD PRIORITIES
 In Java, thread priority determines the order in which
threads are scheduled for execution.
 Each thread has a priority, which helps the thread
scheduler decide the order of thread execution.

Prepared by GSK
 Higher-priority threads are more likely to be executed
before lower-priority ones, though this doesn’t
guarantee execution order due to the nature of thread
scheduling. In Java, when we create a thread, always a
priority is assigned to it.
 The priority is given by the JVM or by the
programmer itself explicitly.
82
 The range of the priority is between 1(Low) to 10(High)
GET AND SET METHODS IN THREAD
PRIORITY

1. int getPriority( )

 In Java, getPriority() method is in java.lang.Thread


package. it is used to get the priority of a thread

Prepared by GSK
2. void setPriority (int newPriority)

 In Java setPriority(int newPriority) method is in


java.lang.Thread package.

 It is used to set the priority of a thread.

 The setPriority() method throws IllegalArgumentException


if the value of new priority is below the minimum and
85

above the maximum limit.


EXAMPLE: FETCH THREAD PRIORITY

 If we don’t set priority of a thread then by


default it is set by the JVM.

Prepared by GSK
 The default priority for a thread is 5
 We can get thread’s priority by
using getPriority( ) method.

86
PROGRAM FOR GETTING DEFAULT PRIORITY OF THREADS

class MyThread extends Thread


{

public static void main(String[ ] args)


{

Prepared by GSK
MyThread p1 = new MyThread();
MyThread p2 = new MyThread();
MyThread p3 = new MyThread();
System.out.println("P1 thread priority : " +
p1.getPriority());
System.out.println("P2 thread priority : " +
p2.getPriority());
System.out.println("P3 thread priority : " +
p3.getPriority()); Output:
P1 thread priority : 5 87
P2 thread priority : 5
}} P3 thread priority : 5
EXAMPLE : SET PRIORITY

 To set priority of a thread, setPriority( ) method of


thread class is used.

Prepared by GSK
 It takes an integer argument that must be
between 1 and 10.

88
class ThreadSetPriority extends Thread
{
public void run()
{
System.out.println("Thread Running...");
}

public static void main(String[]args)

Prepared by GSK
{
ThreadSetPriority p1 = new ThreadSetPriority();

// Starting thread
p1.start();
Output:
// Setting priority Thread Running...
p1.setPriority(2); thread priority : 2

// Getting priority
int p = p1.getPriority();

System.out.println("thread priority : " + p); 89

}} Program to implement setPriority() of threads


SYNCHRONIZING THREADS

Prepared by GSK
suppose that both passengers start their reservation
process at 11 am and observe that only two seats are
available.

First passenger books two seats and simultaneously


the second passenger books one seat.

Prepared by GSK
Since the available number of seats is only two
but booked seats are three. This problem happened
due to asynchronous access to the railway reservation
system.

In this real-time scenario, both passengers can be


considered as threads, and the reservation system
can be considered as a single object, which is
modified by these two threads asynchronously. 91
• This asynchronous problem is known as race
condition in which multiple threads access
the same object/Resource and modify the
state of object inconsistently.

Prepared by GSK
• The solution to this problem can be solved by
a synchronization mechanism in which when
one thread is accessing the state of
object, another thread will wait to
access the same object at a time until
92

their turn come.


WHAT IS THREAD SYNCHRONIZATION?

 Synchronization is a process of handling resource


accessibility by multiple thread requests.

Prepared by GSK
 The main purpose of synchronization is to avoid
thread interference.
 When more than one thread try to access a
shared resource, we need to ensure that resource
will be used by only one thread at a time.
The process by which this is achieved is called
synchronization. 93
THREAD SYNCHRONIZATION? CONTD..

 The synchronized keyword in java creates a


block of code referred to as critical section.

Prepared by GSK
 In other words, when a thread is already
accessing an instance of a class, preventing any
other thread from acting on the same instance is
called ‘thread synchronization in Java‘ or
‘ Thread safe‘.

94
OBJECT LOCK IN JAVA
 The code in Java program can be synchronized with the
help of a lock.

A lock has two operations: acquire and release.

Prepared by GSK

 In Java programming language, every object has a default


object lock that can be used to lock on a thread

 To acquire an object lock on a thread, we call a


method or a block with the synchronized keyword.

 Before entering a synchronized method or a block, a


thread acquires an object lock.
95
OBJECT LOCK IN JAVA CONTD…

 Object lock is like a room with only one door.


A person enters the room and locks the door

Prepared by GSK
from inside. The second person who wants to
enter the room will wait until the first person
come out.

 Similarly, a thread also locks the object after


entering it, the next thread cannot enter it until
the first thread comes out.
96
Prepared by GSK
97
General Syntax:

synchronized (object)
{

Prepared by GSK
//statement to be synchronized
}

Since the code inside the method is synchronized, the


code will not be available to more than one
thread at a time.
98
class Reserve implements Runnable
{
//Available berths are
int available = 1;

Prepared by GSK
int wanted;

//Accept wanted berths at run time


Reserve(int i)
{
wanted = i;
99

}
public void run()
{
//Display available berths
System.out.println("Available berths= "+available);

Prepared by GSK
//available berths are more than wanted berths
if(available>=wanted)
{
//get the name of the person
String name = Thread.currentThread().getName();
//Allot the berth to him
System.out.println(wanted +" Berth(s) reserved for
100

"+name);
try
{
Thread.sleep(2000); //wait for printing the
//ticket 2000 milliseconds (2 seconds)
available = available-wanted;
//update the no. of available berths
}

Prepared by GSK
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
else{
//if available berths are less, display message
System.out.println("Sorry! No berths available");
}
101
}
}
class Unsafe {

public static void main(String[] args) {


//Tell that one berth is needed
Reserve obj = new Reserve(1);

//Attach first thread to the object


Thread t1 = new Thread(obj);

Prepared by GSK
//Attach second thread to the same object
Thread t2 = new Thread(obj);

//take the thread names as persons names


t1.setName("First Person");
t2.setName("Second Person");

//Send the request for berths


t1.start();
OutPut:
t2.start(); Available berths= 1
} Available berths= 1 102
1 Berth(s) reserved for First Person
} 1 Berth(s) reserved for Second Person
 It has allocated the same berth for two peoples.

 In this program, we have already taken available


berths as 1.

Prepared by GSK
 When thread t1 enters the run() method, it sees
available number of berths as 1 and hence, it allots it
to First person.

103
 Then it enters into try{ } block inside the run()
method, where it will sleep for 2 seconds. In this time,
ticket will be printed on the printer. When thread t1 is
sleeping, thread t2 also enters the run() method, it

Prepared by GSK
also sees that there is 1 berth remaining.

 The reason is for this is that the available number of


berths are not yet updated by the first thread.

 So that, thread t2 allots the same berth to the second


person. Then the thread t2 also goes into sleep state.

104
 To solve these problem in java, there is a concept called
synchronization.
 Synchronization will not allow the multiple thread
accessing run() method at a time.

Prepared by GSK
 What Is an InterruptedException?
An InterruptedException is thrown when a thread is
interrupted while it's waiting or sleeping.
 printStackTrace()
The printStackTrace() method
of Java.lang.Throwable class used to print the details
like class name and line number where the exception
105
occurred.
HOW CAN WE SYNCHRONIZE THE OBJECT?

 There are two ways of synchronize the object.


 1. Using synchronized block: Here, we can embed a
group of statements of the object with in a synchronized block,

Prepared by GSK
 synchronized (object)
{
statements;
}
In the above statement object represents the object to be locked
or synchronized. The statements inside the synchronized block
all are available to only one thread at a time
106
 2. Using synchronized method:

 we can synchronize an entire method by using


synchronized keyword. For example, if we want to
synchronize the code of display( ) method, then add

Prepared by GSK
the synchronized keyword before the method name.

synchronized void display( )

statements;

}
107
JAVA DAEMON THREAD
 Daemon threads in Java are special types of
threads that run in the background to perform
tasks such as garbage collection, background clean-

Prepared by GSK
up, etc

 Daemon threads is a low priority thread that


provide supports to user threads.

 These threads can be user defined and system


defined as well.
108
METHODS IN DAEMON THREAD

1. void setDaemon(boolean status)


 In Java, this method is used to create the current

Prepared by GSK
thread as a daemon thread or user thread(Non-
daemon)
 If there is a user thread as obj1 then
obj1.setDaemon(true) will make it a Daemon
thread and if there is a Daemon thread obj2 then
calling obj2.setDaemon(false) will make it a user
thread 109
2. boolean isDaemon()
 In Java, this method is used to check whether
the current thread is a daemon or not.

Prepared by GSK
 It returns true if the thread is Daemon otherwise it
returns false.

 The main difference between Daemon thread and


user threads is that the
❖ JVM does not wait for Daemon thread before exiting
while it waits for user threads, it does not exit until
unless all the user threads finish their execution. 110
Example Program to implement Daemon Thread

public class DaemonThreadExample1 extends Thread


{

public void run()


{

Prepared by GSK
// Checking whether the thread is Daemon or not
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon thread executing");
}
else{
System.out.println("user(normal) thread
executing");
} 111

}
public static void main(String[] args)
{
/* Creating two threads: by default they are
user threads (non-daemon threads) */

DaemonThreadExample1 t1=new
DaemonThreadExample1();

Prepared by GSK
DaemonThreadExample1 t2=new
DaemonThreadExample1();

//Making user thread t1 to Daemon


t1.setDaemon(true);

//starting both the threads


t1.start();
t2.start(); Output:
112
} Daemon thread executing
} user(normal) thread executing
GROUPING OF THREADS
 Thread group presents several threads as a single
group.
 The main advantage of taking several Threads as a

Prepared by GSK
group is that by using a single method, will be able
to control all the threads in a group.
 To create a thread group, we should simply create an
object to ThreadGroup class as:
 ThreadGroup tg= new ThreadGroup(" group name");
 Here tg is ThreadGroup object, and group name is its
113
name.
GROUPING OF THREADS CONTD…
 All the threads of a threadgroup can be stopped
together by calling tg.stop( ) or it can be
suspended by calling tg.suspend( ) or it can be

Prepared by GSK
resumed but calling tg.resume( ) where tg is a
threadgroup object.

A thread is allowed to access information


about its own thread group, but it cannot
access the information about its thread group's
114
parent thread group or any other thread groups.
GROUPING OF THREADS CONTD…

A thread can not be moved to a new group after


the thread has been created.

Prepared by GSK
 When a Java application first starts up, the Java
runtime system creates a ThreadGroup named
main.

 Java thread groups are implemented by the


java.lang.ThreadGroup class.
115
CONSTRUCTORS WITH THREADGROUP

 1)ThreadGroup(String name)

creates a thread group with given name.

Prepared by GSK
 This constructor is used for creating a new thread
group, the parent of this thread group is the same
as the parent group of the currently executing
thread.

116
 2)ThreadGroup(ThreadGroup parent, String name)

creates a thread group with a given parent group and


name.

 This constructor creates a thread group with a

Prepared by GSK
specified thread group as a parent and
specified name.

 This constructor may throw NullPointerException in


case the specified thread group is null, and
SecurityException may be thrown in case the
currently running thread does not have permission to117
create a thread group.
METHODS

 The getName( ) method of ThreadGroup class


returns the name of the thread group.

Prepared by GSK
 getParent( ) method returns the name of the parent
thread group of the current group. i.e. for a
Threadgroup we can create sub groups also. (like we
can create sub packages to packages).
118
METHODS CONTD…

 getMaxPriority( ) this method returns the


maximum priority of thread that can be given to a

Prepared by GSK
thread in a group.

 Threads that are part of the group cannot have a


higher priority than the maximum priority set for a
group.
119
METHODS CONTD…

 activeCount( ) this method returns the


number of the active threads in a group.

Prepared by GSK
 This is a very convenient method to know how
many threads in a group are alive at a
particular moment. In a containing many
threads some Threads must have been already
dead when they completed their Run method
and some may have not been started as by the
120
programmer.
Program to implement ThreadGroups

import java.lang.*;
class Tgroups
{

public static void main(String args[]) throws Exception

Prepared by GSK
{

Reservation res=new Reservation();


Cancellation can=new Cancellation();

// creating the thread group with name


ThreadGroup tg = new ThreadGroup("First Group");

// creating two threads and adding to first group


Thread t1 = new Thread(tg, res, "First Thread");
Thread t2 = new Thread(tg, res, "Second Thread");

121
Program to implement ThreadGroups

// creating another thread group tg1 as a child to tg


ThreadGroup tg1 = new ThreadGroup(tg, "Second Group");

// creating two threads and adding to Second group i.e.,tg1


Thread t3 = new Thread(tg1, can, "Third Thread");

Prepared by GSK
Thread t4 = new Thread(tg1, can, "Fourth Thread");

// Find parent group of tg1


System.out.println("Parent of tg1 is " + tg1.getParent());

// set maxPriority to tg1 as 7


tg1.setMaxPriority(7);

//Know the thread group of t1 and t3


System.out.println("Thread group of t1 is" +
t1.getThreadGroup());
System.out.println("Thread group of t3 is" +
t3.getThreadGroup()); 122
Program to implement ThreadGroups

//start the threads


t1.start();
t2.start();
t3.start();
t4.start();

Prepared by GSK
//Find how many threads are actively running
System.out.println("Number of active threads running in tg group:
"
+ tg.activeCount());
}
}

123
class Reservation extends Thread
{
public void run()
{
System.out.println("I am Reservation Thread");
}
}

Prepared by GSK
class Cancellation extends Thread
{
public void run()
{
System.out.println("I am Cancellation Thread");
}
}
Output:
Parent of tg1 is java.lang.ThreadGroup[name=First Group,maxpri=10]
Thread group of t1 isjava.lang.ThreadGroup[name=First Group,maxpri=10]
Thread group of t3 isjava.lang.ThreadGroup[name=Second Group,maxpri=7]
I am Reservation Thread
I am Reservation Thread
124
I am Cancellation Thread
I am Cancellation Thread
Number of active threads running in tg group: 0
INTER THREAD COMMUNICATION

 In some cases, two or more threads should communicate


with each other.

Prepared by GSK
 For example, a Consumer thread is waiting for a Producer
to produce the data (or some goods). When the Producer
completes production of data, then the consumer thread
should take that data and use it.

125
INTER THREAD COMMUNICATION CONTD…
Method Description
Obj.wait( ) This method makes a thread wait for
the object (obj) till it receives a

Prepared by GSK
notification
Obj.notify( ) This method releases an object (obj)
and sends a notification to a waiting
thread that the object is available.
Obj. This method is useful to send
notifyAll() notification to all waiting threads that
the object (obj) is available

126
 Note:

Prepared by GSK
To make the Producer wait until Consumer
retrieves the item and Consumer wait until
Producer places an item, we can use
the wait() and notify() methods.

127
JAVA ENUMERATIONS
 In Java, an enum (short for enumeration) is a type
that has a fixed set of constant values.
 We use the enum keyword to declare enums.

Prepared by GSK
For example,
enum Size { SMALL, MEDIUM, LARGE,
EXTRALARGE }
 Here, we have created an enum named Size. It
contains fixed values SMALL, MEDIUM, LARGE,
and EXTRALARGE.
 These values inside the braces are called enum
constants (values).
 Note: The enum constants are usually represented 132
in uppercase.
Example Program to Implement Enum

enum Size
{
SMALL, MEDIUM, LARGE, EXTRALARGE

Prepared by GSK
}

class Test
{
Size pizzaSize;

public Test(Size pizzaSize)


{
this.pizzaSize = pizzaSize;
} 133
Example Program to Implement Enum Contd..

public void orderPizza() {


switch(pizzaSize) {
case SMALL:
System.out.println("I ordered a small size pizza.");
break;
case MEDIUM:
System.out.println("I ordered a medium size pizza.");

Prepared by GSK
break;
default:
System.out.println("I don't know which one to order.");
break;
}
}
}

class Enum_Ex {
public static void main(String[] args) {
Test t1 = new Test(Size.MEDIUM);
t1.orderPizza();
} 134
Output:
} I ordered a medium size pizza.
Example-2: Implementing enum

// Define an enum type


enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,

Prepared by GSK
THURSDAY, FRIDAY, SATURDAY
}

public class EnumExample {


public static void main(String[] args) {
// Create a variable of the enum type
Day today = Day.WEDNESDAY;

// Use the enum in a switch statement


135
Example-2: Implementing enum Contd…
switch (today) {
case MONDAY:
System.out.println("Start of the work week!");
break;
case WEDNESDAY:
System.out.println("Midweek, hang in there!");

Prepared by GSK
break;
case FRIDAY:
System.out.println("Almost the weekend!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("It's the weekend, enjoy!");
break;
default:
System.out.println("Just another day!");
break;
} Output:
136

} Midweek, hang in there!


}
JAVA AUTOBOXING AND UNBOXING

 In autoboxing, the Java compiler automatically


converts primitive types into their corresponding
wrapper class objects.

Prepared by GSK
For example,

int a = 56;

Integer aObj = a; // autoboxing

❖ Autoboxing has a great advantage while working


with Java collections.
137
Example Program to implement autoboxing

import java.util.ArrayList;

class Main Output:


{ ArrayList: [5, 6]
public static void main(String[] args)
{

Prepared by GSK
ArrayList<Integer> list = new ArrayList<>();

//autoboxing
list.add(5);
list.add(6);

System.out.println("ArrayList: " + list);


}
}

we have created an array list of Integer type. Hence the array list can only
hold objects of Integer type. Notice the line,list.add(5); Here, we are passing
primitive type value. However, due to autoboxing, the primitive value138 is
automatically converted into an Integer object and stored in the array list.
UNBOXING

 In unboxing, the Java compiler automatically


converts wrapper class objects into their
corresponding primitive types.
 For example,

Prepared by GSK
// autoboxing
Integer aObj = 56;

// unboxing
int a = aObj;

❖ Like autoboxing, unboxing can also be used with


Java collections.
139
Example Program to implement Unboxing
import java.util.ArrayList;
class Main {
Output:
public static void main(String[] args) {
ArrayList: [5, 6]
Value at index 0: 5
ArrayList<Integer> list = new ArrayList<>();

//autoboxing

Prepared by GSK
list.add(5);
list.add(6);

System.out.println("ArrayList: " + list);

// unboxing
int a = list.get(0);
System.out.println("Value at index 0: " + a);
}
}
notice the line,
int a = list.get(0); Here, the get() method returns the object at index 0.
140
However, due to unboxing, the object is automatically converted into
the primitive type int and assigned to the variable a.
JAVA ANNOTATIONS

 Java annotations are metadata (data about


data) for our program source code.

Prepared by GSK
 They provide additional information about
the program to the compiler but are not part
of the program itself.

 can influence code behaviour

 Annotations start with @.


141

 Its syntax is: @AnnotationName


JAVA ANNOTATIONS CONTD..

 Let's take an example of @Override annotation.


 The @Override annotation specifies that the method

Prepared by GSK
that has been marked with this annotation
overrides the method of the superclass with the
same method name, return type, and parameter list.
 It is not mandatory to use @Override when
overriding a method. However, if we use it, the
compiler gives an error if something is wrong (such
as wrong parameter type) while overriding the 142

method.
class Animal
{ Example Program to implement
public void displayInfo() @Override annotation
{
System.out.println(“From animal class");
}
}
Output:
class Dog extends Animal

Prepared by GSK
From dog class
{
@Override
public void displayInfo()
{
System.out.println(“From dog class");
}
}
class Annotation_Ex
{
public static void main(String[] args)
{
Dog d1 = new Dog();
143
d1.displayInfo();
}
}
GENERICS

 Java Generics allows us to create a single class,


interface, and method that can be used with

Prepared by GSK
different types of data (objects).

 This helps us to reuse our code.

 Note: Generics does not work with primitive types


(int, float, char, etc).

144
JAVA GENERICS METHOD
we can create a method that can be used with any
type of data, is known as Generics Method.

Program to implement Java Generics

Prepared by GSK
class DemoClass
{

// create a generics method


public <T> void genericsMethod(T data)
{
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
} 145

}
JAVA GENERICS METHOD CONTD…
class Generics_Ex
{
public static void main(String[] args)
{

Prepared by GSK
// initialize the class with Integer data
DemoClass demo = new DemoClass();

// generics method working with String


demo.<String>genericsMethod("Java Programming");

// generics method working with integer


demo.<Integer>genericsMethod(25);
} Output:
} Generics Method:
Data Passed: Java Programming 146
Generics Method:
Data Passed: 25
 In the Previous example, we have created a generic
method named genericsMethod.

 public <T> void genericMethod(T data) {...}

 Here, the type parameter <T> is inserted after the


modifier public and before the return type void.

 We can call the generics method by placing the actual


type <String> and <Integer> inside the bracket before
the method name.

 demo.<String>genericMethod("Java Programming");

 demo.<Integer>genericMethod(25); 147

You might also like