Java Unit-3 Final
Java Unit-3 Final
07 08
Synchronizing threads Interthread
TOPIC TOPIC Communication.
Exception-Handling Fundamentals
An exception is an abnormal condition that arises in a code at run time. In other words, an exception is a
runtime error.
When an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
An exception can occur for many different reasons, below given are some scenarios where exception
occurs.
i. Division by zero
ii. Array out of bound access exception
iii. A user has entered invalid data.
iv. A file that needs to be opened cannot be found.
v. A network connection has been lost in the middle of communications
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Exception-Handling
“Exception handling is the mechanism to handle run time errors, so that the normal flow of application can
be maintained.”
Exception Handling is managed by using 5 Keywords.
1. try
2. catch
3. throw
4. throws
5. finally
Types of Java Exceptions
There are mainly three types of exceptions:
i. User Defined Exceptions
ii. Built in Exceptions
i. Checked Exception
ii. Unchecked Exception
Types of Exceptions
[Link] exceptions:
A checked exception is an exception that occurs at the compile time, these are also called as compile
time exceptions.
These exceptions cannot simply be ignored at the time of compilation, the Programmer should take care
of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file specified in
its constructor doesn't exist, then an FileNotFoundException occurs, and compiler prompts the
programmer to handle the exception.
[Link] exceptions
1. ClassNotFoundException: This exception is thrown when the JVM tries to load a class, which is not
present in the classpath.
[Link]("[Link]
er");
2. FileNotFoundException: This exception is thrown when the program tries to access a file that does not
exist or does not open. This error occurs mainly in file handling programs.
Thread t = new
Thread();
[Link](10000);
Types of Exceptions
import [Link];
import [Link];
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file=new File("E://[Link]");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program you will get exceptions as shown below.
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.jav[Link] error: unreported exception FileNotFoundException; must be caught or declared
to be thrown
FileReader fr = new FileReader(file);
^
1 error
Some of the examples of checked exceptions
Types of Exceptions
[Link] exceptions:
An Unchecked exception is an exception that occurs at the time of execution, these are also called as
Runtime Exceptions.
These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of
the array then an ArrayIndexOutOfBoundsException occurs.
To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a
try block.
Immediately following the try block, include a catch clause that specifies the exception type that you
wish to catch.
[Link] exceptions
[Link]: This exception occurs when a program encounters an error in arithmetic operations
class Test
such as divide by zero. {
public static void OUTPUT
main(String[] args) D:\>java Test
{ Exception in thread "main"
[Link]: /
[Link](120/0); by zero
}
}
[Link]: This exception is thrown when an array is accessed using an illegal
index. The index usedclass
is either more than the size of the array or is a negative index. Java doesn’t support
Test
negative indexing. {
public static void OUTPUT
main(String[] args) D:\>java Test
{ Exception in thread "main"
int[] a = {10,20,30}; [Link]
dsException: Index 50 out of
[Link](a[50]); bounds for length 3
}
[Link] exceptions
[Link]: This exception is raised when a null object is referred to in a program.
NullPointerException
class Test is the most important and common exception in Java.
{
OUTPUT
public static void
D:\>java Test
main(String[] args)
Exception in thread "main"
{
[Link]:
String s = null;
Cannot invoke "[Link]()" because
"<local1>" is null
[Link]([Link]());
at [Link]([Link])
}
}
[Link]:class
This Test
exception is thrown when a method could not convert a string
{
into a numeric format.
public static void
main(String[] args)
{
String a = "abc";
int
num=[Link](a);
}
[Link] exceptions
5. StringIndexOutOfBoundsException: This exception is thrown by the string class, and it indicates that the
index is beyond the size of the string object or is negative.
class Test
{
public static void main(String[] args)
{
String a = "JAVA";
char c = [Link](6); // accessing 6
index element
[Link](c);
}
}
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
finally
{
// block of code to be executed after try block ends
}
USING TRY AND CATCH
ExceptionType is the type of exception that has occurred.
Program Statements that we monitor for exceptions are contained in try block.
If an exception occurs in try block, it is thrown.
The code can catch this exception using catch block and handle the exception in a rational manner.
System generated exceptions are automatically thrown by the Java runtime.
Catch block is used to handle the exception, called Exception Handler.
Must be used after try block only. We can use multiple catch blocks with a single try block.
The throw keyword is used to manually throw an exception
Any code that absolutely must be executed after a try block completes is put in finally block.
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
}
catch (ArithmeticException e)
{
[Link]("Division by zero.");
} Output
[Link]("After catch statement."); Division by zero.
After catch statement
}
}
MULTIPLE CATCH CLAUSES
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each catching a different
type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one whose type
matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues after the
try/catch block. try
{
Syntax of Multiple catch statements: // block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
MULTIPLE CATCH CLAUSES
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[])
{
try
{
int a = [Link];
[Link]("a = " + a); Output
int b = 42 / a; a = 10
int c[] = { 1 }; Array index oob:
c[42] = 99; [Link]:
} Index 42 out of bounds for length 1
catch(ArithmeticException e) After try and catch blocks.
{
[Link]("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index oob: " + e);
}
[Link]("After try and catch blocks.");
}
}
NESTED TRY STATEMENTS
The try statement can be nested.
That is, a try statement can be inside the block of another try.
Each time a try statement is entered, the context of that exception is pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception, the stack is unwound
and the next try statement’s catch handlers are inspected for a match.
This continues until one of the catch statements succeeds, or until the entire nested try statements are
exhausted.
If no catch statement matches, then the Java run-time system will handle the exception. Here is an
example that uses nested try statements:
// An example of nested try statements.
class NestTry
{
public static void main(String args[])
{
try
{
int a[] = {1,2,3,0,4};
try
{
int b=a[2]/a[3];
}
OUTPUT:
catch(ArithmeticException e)
C:\>java NestTry
{ [Link]: / by zero
[Link]( e); [Link]
}
a[20]=44;
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
}}
THROW
So far, you have only been catching exceptions that are thrown by the Java run-time system.
However, it is possible for your program to throw an exception explicitly, using the throw statement
throw keyword is used to explicitly throw an exception from a method or constructor.
We can throw either checked or unchecked exceptions in java by throw keyword.
The "throw" key-word is mainly used to throw a custom exception.
When a throw statement is encountered, program execution is halted, and the nearest catch statement is
searched for a matching kind of exception.
The general form of throw is shown here: Syntax
throw
ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Example-1 Example-2
throw new throw new ArithmeticException(“Something
ArithmeticException( ); went wrong!”);
// Demonstrate throw.
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
[Link]("Exception caught“+e);
}
}
Syntax
<return_type> <method_name> ( ) throws <excpetion_name1>, <exception_name2>
{
// body of method
}
Example
void Display( ) throws ArithmeticException, NullPointerException
{
//code
}
class Test
{
static void check() throws ArithmeticException
{
[Link]("Inside check function");
throw new ArithmeticException("demo");
}
Syntax
class <name of the class> extends Exception
{
public String toString()
{
Statements;
}
}
Creating own exception
Example
class MyException extends Exception
{ class Test
String str1; {
MyException(String s) public static void main(String args[])
{ {
str1=s; try
} {
public String toString() [Link]("Starting of try block");
{ throw new MyException("This is My error Message");
return ("MyException Occurred: "+str1) ; }
} catch(MyException exp)
} {
[Link]("Catch Block") ;
[Link](exp) ;
}
OUTPUT
}
Starting of try block
Catch Block }
MyException Occurred: This is My error Message
Example
class InsufficientFundsException extends Exception else
{ throw new InsufficientFundsException("No Balance in your account");
InsufficientFundsException(String s) }
{ catch (InsufficientFundsException e)
super(s); {
} [Link]([Link]());
} }
class Test finally
{ {
public static void main(String[] args) [Link]("Updated Balance:"+balance);
{ [Link]("Pls take your card");
[Link] obj = new }
[Link]([Link]); }
double balance = 10000.00; }
double amt = [Link]();
try
{
if(amt<=balance)
{
[Link]("pls take the cash");
OUTPUT
balance = balance - amt;
}
Multi Threading
Multi Threading is a specialized form of multi tasking.
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
Executing several tasks simultaneously where each task is a separate independent process such type of
multitasking is called process based multitasking.
Executing several tasks simultaneously where each task is a separate independent part of the same
program, is called Thread based multitasking. And each independent part is called a "Thread"
Multithreading refers to a process of executing two or more threads simultaneously for maximum
utilization of the CPU.
Multithreading is a feature in Java that concurrently executes two or more parts of the program.
Multi Threading
A thread in Java is a lightweight process requiring fewer resources.
Each thread runs parallel to each other. A thread is a lightweight subprocess,
the smallest unit of execution within a
Java Provides built in support for multi threaded programming. program.
It allows multiple parts of a program
Threads share common memory area. to run concurrently
A main program is also single thread.
Advantages of MultiThreading
Allows to write very efficient program that makes maximum use of CPU.
Throughput – Amount of work done in unit time increase.
It is used to save time as multiple operations are performed concurrently.
The threads are independent, so it does not block the user to perform multiple operations at the same
time.
Since threads are independent, other threads don’t get affected even if an exception occurs in a single
thread.
• Multi Threading : It allows concurrent execution of two or
more parts of a program for maximum utilization of CPU.
run()
start()
Thread Life Cycle
i. New: The thread is in new state when the instance of thread class is created but before the calling of start()
method.
ii. Runnable: The thread is in runnable state after the invocation start() method, but the thread scheduler has
not selected it to be the running thread. Any number of threads exists in this state.
iii. Running: The thread is in running state when the thread scheduler selects a thread for execution.
iv. Waiting/blocked/sleeping: this is the state when the thread is still alive but is not eligible currently to run.
v. (Blocked) Terminated: A thread is in terminated or dead state when its run() method exits.
We can define a Thread in the following 2 ways.
i. By extending Thread class.
ii. By implementing Runnable interface
Thread class :
Multi Threading
The main important application areas of multithreading are:
To implement multimedia graphics.
To develop animations.
To develop video games etc.
To develop web and application servers.
Thread class:
Java provides Thread class to achieve thread programming.
Thread class provides constructors and methods to create and perform operations on a thread.
Commonly used Constructors of Thread class:
[Link] static Thread currentThread(): returns the reference of currently executing thread.
8. Public static void sleep(long miliseconds): Causes the currently executing thread to suspend (temporarily
[Link] boolean isAlive(): to check the thread is still running. Returns true if the thread is still running.
[Link] void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
Create a new class that extends Thread, and then create an instance of that class.
Step-2:
The extending class must override the run () method, which is the entry point of the
new thread created. The actual code for the thread to execute is provided. Once the run ()
method completes, the thread will die and terminate.
Step-3:
i. Mutual Exclusion
ii. Inter Thread communication.
Synchronizing Threads
1. Mutual Exclusion
Keeps threads away from interfering with one another while sharing data. Allows only one thread to access
shared data. Mutual exclusive threads can be implemented using
i) Synchronized Method ii) Synchronized Block
i) Synchronized Method
A method defines as synchronized, then the method is a synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires lock for that object and releases it
when the thread completes its task. The form of synchronized method is:
class Table
{
synchronized type methodName(arguments)
{
//method body for Synchronization
}
}
Bus Reservation System using synchronization:
1. Multiple passengers (threads) try to book seats on the bus
simultaneously.
2. Without synchronization, two threads could book the same seat,
causing conflicts.
3. Using synchronized methods or blocks, only one thread can access
the booking process at a time.
4. This ensures that the seat availability is checked and updated
atomically for each passenger.
5. Synchronization prevents race conditions and maintains data
consistency in the reservation system.
//synchronized Method - for Synchronization Synchronizing Threads
class Table OUTPUT
{
8x1=8
synchronized void printTable(int n) class MyThread2 extends Thread
{ { 8x2=16
try{ Table t; 8x3=24
for(int i=1;i<=10;i++) MyThread2(Table t) 8x4=32
{ {
[Link](n+"x"+i+"="+n*i); this.t=t;
8x5=40
[Link](1000); } 8x6=48
} public void run() 8x7=56
} { 8x8=64
catch(InterruptedException e) [Link](9);
{ [Link](e); } 8x9=72
} } 8x10=80
} public class SyncDemo1 9x1=9
} {
9x2=18
class MyThread1 extends Thread public static void main(String args[])
{ { 9x3=27
Table t; Table obj = new Table(); 9x4=36
MyThread1(Table t) MyThread1 t1=new MyThread1(obj); 9x5=45
{ MyThread2 t2=new MyThread2(obj);
this.t=t; [Link]();
9x6=54
} [Link](); 9x7=63
public void run() } 9x8=72
{ } 9x9=81
[Link](8);
} 9x10=90
}
Synchronizing Threads
ii) Synchronized Block:
Synchronized block can be used to perform synchronization on any specific resource of a method.
Synchronized block is used to lock an object for any shared resource.
Scope of Synchronized block is smaller than the method.
i. wait()
ii. notify()
iii. notifyAll()
All the three methods must be called only from within a synchronized context.
All these methods are related to lock and the object has a lock.
InterThread Communication
i. wait():
Tells the calling thread to given up the monitor(lock) and go to sleep until some other thread enters
the same monitor and calls notify().
public final void wait() throws InterruptedException
public final void wait(long time) throws InterruptedException
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method
for this object.
InterThread Communication
•ii. notify():
wakes up a single thread that is waiting on this object's monitor. If many 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. A
thread waits on an object's monitor by calling one of the wait methods.
public final void notify()
•[Link]()
wakes up all thread called wait() on the same object. One of the thread will be
granted access. Wakes up all the waiting threads.
public final void notifyAll()
Producer Consumer Problem for Interthread Communication
Producer Thread- Produce items to Buffer (Add Items) Consumer Thread- Consume
items from Buffer (Removes Items).
The two conditions for Producer – Consumer Problem is
1. Producer cannot add an item into a buffer if it is full
2. Consumer cannot consume an item if it is empty.
If no communication, these two conditions are not satisfied then the CPU is always in
polling (loop).
To Save CPU time in Java Interthread communication is used.
Producer Consumer Problem
//Producer-Consumer problem ---> Inter Thread Communication.
for Interthread Communication
class Buffer
{
int item; synchronized int consume()
boolean produced = false; {
synchronized void produce(int x) if(!produced)
{ {
if(produced) try{
{ wait();
try{ }
wait(); catch(InterruptedException ie)
} {
catch(InterruptedException ie) [Link]("Exception Caught " +ie);
{ }
[Link]("Exception }
Caught"); [Link]("Consumer - Consumed " +item);
} produced = false;
} notify();
item =x; return item;
[Link]("Producer - Produced-->" +item); }
produced =true; }
notify();
}
Producer Consumer Problem for Interthread Communication
class Consumer extends Thread
{
class Producer extends Thread Buffer b;
{ Consumer(Buffer b)
Buffer b; {
Producer( Buffer b) this.b = b;
start();
{
}
this.b = b; public void run()
start(); {
} [Link]();
public void run() [Link]();
{ [Link]();
[Link](10); [Link]();
[Link](20); }
}
[Link](30);
public class PCDemo
[Link](40); {
[Link](50); public static void main(String args[])
} {
} Buffer b = new Buffer(); //Synchronized Object
Producer p = new Producer(b);
Consumer c = new Consumer(b);
}
}
N
H A ‘Q
T
’