0% found this document useful (0 votes)
38 views

Module 3 - Java Programming

The document discusses exception handling and threads in Java. It covers types of exceptions like errors and exceptions, how to handle exceptions using try, catch, throw, throws and finally. It also discusses user defined exceptions, predefined exceptions like NullPointerException, and the hierarchy of exception classes in Java. For threads, it explains the fundamentals of multithreading, advantages of multithreading, thread life cycle states like new, runnable, running, blocked and terminated.

Uploaded by

Pratham Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Module 3 - Java Programming

The document discusses exception handling and threads in Java. It covers types of exceptions like errors and exceptions, how to handle exceptions using try, catch, throw, throws and finally. It also discusses user defined exceptions, predefined exceptions like NullPointerException, and the hierarchy of exception classes in Java. For threads, it explains the fundamentals of multithreading, advantages of multithreading, thread life cycle states like new, runnable, running, blocked and terminated.

Uploaded by

Pratham Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 106

Module 3 : Exception Handling & Threads

• Exception Handling
– Exceptions & Errors
– Types of Exception
– Control Flow in Exceptions
– Use of try, catch, throw, throws, finally, in
Exception Handling
– User Defined Exceptions
Error
• Errors are beyond the control of the
programmers.
• The errors cannot be recovered which means
we cannot handle it through the program. To
avoid the error, the programmer must follow
the rules of the particular programming
language.
• These are the problems raised in the program
at compile time. For example, the syntactical
mistake (missing semicolon, exclamatory
symbol, misspelling the keyword) is the best
example of an error and these problems are
identified during the compilation time.
Exceptions
• Exceptions are abnormal conditions in a
program which leads to abort the program.
• Runtime error in the program and it can be
recovered. It means, we can handle the
exception through the program.
• An unexpected event that abrupt the normal
execution of the program is called exception.

• Abnormal situation or invalid events which


occurs during the execution time of the
program
Real time examples of Exception
• Imagine that you have developed a program to
read only the numbers as inputs, and by
mistake if you read an alphabet or a string.
What is the impact of the output and how to
handle this situation?

• Assume that you are searching a file in the hard


disk, if it is not available, then how to handle
this situation?
• If an exception occurs within a function/method,
then the exception handling mechanism in the
function will create an object and report this
abnormal situation during execution time.

• The objective of handling exceptions is to inform


the user about unexpected situation and to take
an alternative path to overcome the problem and
complete smooth running of the execution
• Through exception handling mechanism, the
user can convert system generated exception
message into an user defined message, so that
it is easy to understand the problem
Hierarchy of Java Exception classes
Syntax
• Throwable class is the base for handling the
exceptions.
• Error and Exception are the derived classes of
Throwable class.
• The Error class deals with the events from
which it is generally not possible to recover
and it should not be caught.
• An example of a non-recoverable error is out of
memory which depends on the hardware and it
cannot be controlled by Java Exception
handling mechanism.
• The Exception class deals with the events from
which it is possible to recover and it can be
handled.
• An example of exception type is divide by zero.
Predefined Exceptions
• ArithmeticException
• ArrayIndexOutOfBoundsException
• NumberFormatException
• FileNotFoundException
• IOException
• NullPointerException
Arithmetic Exception
ArrayIndexOutOfBoundsException
NumberFormatException
NullPointerException
FileNotFoundException
Multiple catch statements
throw
finally
• It is always good practice to use finally clause
after the try and catch block because the finally
block always executes irrespective of exception.
• It is the keyword and it can be used to
– Close the files
– Close the opened connections in the database
– Close the network sockets
– Release the system memory
Guidelines to be followed
• “finally” is not mandatory in exceptional handling
and is optional.
• finally block will not be executing without try block.
• If the finally block is defined before the catch block,
then the program will raise compiler error.
• Multiple finally blocks cannot be defined for single
try block.
• finally block will run without declaring the catch
block
User Defined Exceptions
• 3 ways of creating the user defined exceptions
• Using the subclass of “Exception”
• Using Throwable Class
• Using throw clause
User defined Exception

• package exception; • }
• }
• // class representing custom exception •
• class InvalidAgeException extends Exception • // main method
• { • public static void main(String args[])
• public InvalidAgeException (String str) • {
• { • try
• // calling the constructor of parent Exception • {
• super(str); • // calling the method
• } • validate(13);
• } • }
• // class that uses custom exception • catch (InvalidAgeException ex)
InvalidAgeException • {
• public class TestCustomException1 • System.out.println("Caught the exception");
• { •
• // method to check the age • // printing the message from
• static void validate (int age) throws InvalidAgeException object
InvalidAgeException{ • System.out.println("Exception occured: " +
• if(age < 18){ ex);
• // throw an object of user defined exception • }
• throw new InvalidAgeException("age is not •
valid to vote"); • System.out.println("rest of the code...");
• }
Output
Throwable
User defined exception using throw
Multithreading
Multithreading
• Multithreading in java is a process of executing
multiple threads simultaneously.
• A Multi threaded program contains two or more parts
that can run concurrently.
• Each part of a program is called a thread.
• Multi threading is a specialized form of multi tasking.
Multitasking Fundamentals
• Multitasking is a process of executing multiple tasks
simultaneously.
• We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
Multi Threading Fundamentals
Process based multi tasking:
• A feature that allows to execute two or more programs
concurrently.
• Here a program is the smallest unit of code that can be dispatched
by the scheduler.
Eg: running the java compiler, using text editor or browsing the
internet simultaneously…
Thread based Multitasking:
• Here the thread is Smallest unit of dispatchable code.
• single program can perform two or more tasks at once.
Eg: a text editor can be formatting text at the same time that it is
printing, as long as these two actions are being performed by two
separate threads.
Process-based vs. Thread-based

1. A process is a program that is 1. A thread is a separate path of


executing. execution.

2. Processes are heavy weight tasks 2. Threads are light weight process.
that require their own separate They share the same address space
address spaces.
3. Interprocess communication is
3. Inter thread communication is
expensive and limited.
inexpensive.

4. Context switching from one


4. Context switching from one thread
process to another is also costly.
to the next is low cost.
What is Thread in java

• A thread is a lightweight sub


process, a smallest unit of
processing.
• It is a separate path of execution.
• Threads are independent, if there
occurs exception in one thread,
it doesn't affect other threads.
• It shares a common
memory area.
Advantages of Java Multithreading

• It doesn't block the user because threads are


independent and you can perform multiple operations
at same time.
• You can perform many operations together so it
saves time.
• Threads are independent. so it doesn't affect other
threads if exception occur in a single thread.
Thread Life Cycle
Thread can exist in several states:
The life cycle of the thread in java is controlled by JVM.
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
Thread Life Cycle
Thread can exist in several states:
New State:
• After the creations of Thread instance the thread is in this state but before
the start() method invocation. At this point, the thread is considered not alive.
Ready (Runnable) State:
• A thread start its life from Runnable state.
• A thread first enters runnable state after the invoking of start() method but a
thread can return to this state after either running, waiting, sleeping or
coming back from blocked state also.
• On this state a thread is waiting for a turn on the processor.
Thread Life Cycle (Contd..)
Running State:
• A thread is in running state that means the thread is currently
executing.
• There are several ways to enter in Runnable state but there is
only one way to enter in Running state: the scheduler select a
thread from runnable pool.
Blocked State:
• A thread can enter in this state because of waiting the resources
that are hold by another thread.
Dead State:
• A thread can be considered dead when its run() method completes.
• If any thread comes on this state that means it cannot ever run
again.
Thread Life Cycle
Thread Life Cycle (Contd..)
• Starting from the birth of a thread, till its death, a thread exists in
different states which are collectively called “Thread Life
Cycle”.
• A thread will be born when it is created using Thread class as:
Thread obj=new Thread();
• A thread goes into runnable state when start() method is applied
on it.
• That is void start() method is used to call the public void run()
method.
• From runnable state, a thread may get into non-runnable state,
when sleep() or wait() or suspend() methods act on it.
• notify() and resume() methods are used to restart waiting and
suspended threads respectively.
Thread Life Cycle (Contd..)

• yield() method causes the currently executing thread object to


temporarily pause and allow other threads to execute.
• ThreadDeath class will be invoked whenever the stop() method
is called.
The Thread class and Runnable interface
• Java’s multithreading is built on the Thread class and its
companion interface, Runnable.
• Both are packaged in java.lang package.
• In every java program, there is always a thread running internally.
This thread is used by JVM to execute the program statements.
• When a Java program starts up, one thread begins running
immediately.
• This is usually called the main thread of your program, because it
is the one that is executed when your program begins.
main Thread
The main thread is important for two reasons:
• It is the thread from which other “child” threads will be
spawned.
• Often it must be the last thread to finish execution because it
performs various shutdown actions.
Creating A Thread
• Java defines two ways of creating a Thread.
1. By Implementing Runnable interface.
2. By Extending The Thread class.
Creating A Thread :By Implementing Runnable interface.

• We have an interface called Runnable with only one method


public void run().
interface Runnable
{
public void run();
}
• The class which implements Runnable interface has to
implement the method run().
• Inside run() we can define the code.
• run() can also call other methods.
• After instantiating the class we will pass it to Thread class
– Thread(Runnable obj);
Creating A Thread :By Implementing
Runnable interface.
General form:
class classname implements Runnable
{
public void run()
{
// write code
}
}
class Tdemo
{ public static void main(String args[])
{
//create object of the above class say obj
Thread t1= new Thread(obj);
t1.start();
}}
Creating A Thread :By Implementing Runnable interface.

class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  

Runnable Interfaces
Output
Creating A Thread :By Extending Thread
class
General form:
class classname extends Thread{
public void run(){ //write code here}
}
class Tdemo{
public static void main(String args[]){
//create the object for above class say t1
//call start() method of Thread class
t1.start();
}
}
Creating A Thread :By Extending
Thread class
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
Output:
• thread is running….
Output
Extending Thread vs Implementing Runnable
interface
Extending Thread Implementing Runnable interface
class A extends Thread Class A implements runnable
{ public void run() { } } {public void run() { }
class Ademo{ }
A a1=new A(); Class Ademo{
a1.start(); A a1=new A();
} Thread t=new Thread(a1);
t1.start();}

We can override the other methods of We can only implement only run
thread also along with run(). method.
We can not inherit other classes. We can inherit other classes also.
Methods in Thread class
• currentThread() method returns a reference
to the currently executing thread object.
• getName() method returns this thread's name.
Method Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
isAlive() checks if thread is still running or
not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified
time
start() start a thread by calling run()
method
Constructors of Thread class

• Thread ( )
• Thread ( String str )
• Thread ( Runnable r )
Thread Class Constructors
1. Thread() Allocates a new Thread Object.
E.g., Thread t=new Thread();

2. Thread(String name) Allocates a new thread.


E.g., Thread t= new Thread( “FirstChild”);

3. Thread(Runnable target) Allocates a new Thread object.


E.g., SecondThread st= new SecondThread();
Thread t=new Thread(st);
Thread ( ) and Thread ( String str )

• First constructor is used to create object of thread class. 


Second constructor is also used to create object of thread class with
required name. 
Eg: 
1)Thread t1=new Thread(); 
This creates a thread class object t1. 
2)Thread t2=new Thread(“MYTHREAD”); 
This also creates Thread class object t2 .
It also creates thread with name "MYTHREAD". 
Thread Class Constructors
• Thread ( Runnable r )
• Thread ( Runnable r, String str)

3. Thread(Runnable target)
E.g: SecondThread st= new SecondThread();
Thread t=new Thread(st);

4. Thread(Runnable target, String name)


            E.g:
SecondThread st=new SecondThread();
Thread t= new Thread(st, ”Secondchild”);
Determining when a Thread ends

In java, isAlive() and join() are two different methods to check


whether a thread has finished its execution.
isAlive() :
• This method tests if the thread is alive.
• A thread is alive if it has been started and has not yet died.
join():
• This method waits for thread to die.
• It causes currently running thread to stop executing until the
thread it joins complete its task.
Example

public class ThreadDemo extends Thread


public class ThreadDemo extends Thread
{
{
public void run()
public void run()
{
{
System.out.println("status = " + isAlive());
// tests if this thread is alive
}
System.out.println("status = " + isAlive());
public static void main(String args[])
}
throws Exception
public static void main(String args[]) throws
Exception {
{ ThreadDemo th=new ThreadDemo ();
ThreadDemo t=new ThreadDemo (); th.start();
t.start(); try{
System.out.println("status = " + t.isAlive()); th.join();
} }
} catch(Exception e) {}
System.out.println("status = " +
th.isAlive());
}
}
Join()
Thread ( ) Constructors
Thread(String name)
Thread(Runnable target)
Thread
Thread Priorities
• Each thread have a priority. Priorities are represented by a number between 1 and 10.

• In most cases, thread scheduler schedules the threads according to their priority (known

as preemptive scheduling).

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

The value of MAX_PRIORITY is 10.


Get and Set Thread Priority

• public final int getPriority()


 This method returns priority of given thread.

• public final void setPriority(int newPriority)


 This method changes the priority of thread to the value newPriority.
 This method throws IllegalArgumentException if value of parameter newPriority
goes beyond minimum(1) and maximum(10) limit.
Example
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.start();
m2.start();
}
}
Synchronization
• When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a
time.
• Synchronization used to solve data inconsistency.
• Synchronization is a mechanism to ensure that a resource is shared by one
thread at a time.
Eg: When one thread is writing to a file, a second thread must be
prevented from doing so at the same time
• Key to synchronization in java is the concept of monitor.
• A monitor is an object that is used as a lock. Only one thread can own a
monitor at a given time.
• All objects in java have a monitor object by default. Thus all object
supports synchronization.
• When a thread enters into the monitor all other threads attempting to
enter the locked monitor will be suspended until the first thread exits the
monitor.
Synchronization
•If we do not use syncronization, and let two or more threads access a
shared resource at the same time, it will lead to distorted results.

•Consider an example, Suppose we have two different threads T1 and T2,


T1 starts execution and save certain values in a file temporary.txt which
will be used to calculate some result when T1 returns.

• Meanwhile, T2 starts and before T1 returns, T2 change the values saved


by T1 in the file temporary.txt (temporary.txt is the shared resource). Now
obviously T1 will return wrong result.

•To prevent such problems, synchronization was introduced. With


synchronization in above case, once T1 starts using temporary.txt file, this
file will be locked(LOCK mode), and no other thread will be able to
access or modify it until T1 returns.
How to implement Synchronization
 Synchronization can be achieved in two ways by using
1) Synchronized methods
2) Synchronized statements/Block
 These two ways use the keyword synchronized keyword to
implement synchronization
Without Synchronization
Synchronization
Synchronization Example 2
Inter thread communication
Java Support interthread communication through keywords wait(),notify(),
notifyAll().
Interthread communication:wait()
Wait general forms:
1. final void wait() throws InterruptedException
2.final void wait(long miilis) throws InterruptedException
3.final wait(long millis,long nanos) throws InterruptedException

• The first form waits until it is notified


• The second form waits unitl it is notified or until the specified period of
milliseconds has expired.
• The third form allows you to specify the wait period in terms of
milliseconds and nanoseconds.
Interthread communication:
notify(),notifyAll()
Java Support interthread communication through keywords wait(),notify(),
notifyAll().
General form of notify() and notifyAll():
1.final void notify()
2. final void notifyAll()

A call to notify() resumes one waiting thread.


A call to notifyAll() notifies all threads, with the highest priority thread
gaining access to the object.
Example
Producer consumer problem
• wait( ) tells the calling thread to give up the
monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
• notify( ) wakes up a thread that called wait( ) on
the same object.
• notifyAll( ) wakes up all the threads that called
wait( ) on the same object. One of the threads
will be granted access.
Producer consumer problem
• Problem
To make sure that the producer won’t try to add data into the buffer if
it’s full and that the consumer won’t try to remove data from an empty
buffer.
• Solution 
The producer is to either go to sleep or discard data if the buffer is full.
The next time the consumer removes an item from the buffer, it notifies
the producer, who starts to fill the buffer again. In the same way, the
consumer can go to sleep if it finds the buffer to be empty. The next
time the producer puts data into the buffer, it wakes up the sleeping
consumer.
An inadequate solution could result in a deadlock where both processes
are waiting to be awakened.
Producer consumer problem
• Inside get( ), wait( ) is called. This causes its execution to
suspend until the Producer notifies you that some data is
ready.
• When this happens, execution inside get( ) resumes.
• After the data has been obtained, get( ) calls notify( ). This
tells Producer that it is okay to put more data in the queue.
• Inside put( ), wait( ) suspends execution until the
Consumer has removed the item from the queue. When
execution resumes, the next item of data is put in the queue,
and notify( ) is called. This tells the Consumer that it
should now remove it.
Producer consumer problem
• This program consists of four classes:
• Q, the queue that you're trying to synchronize;
• Producer, the threaded object that is producing queue entries;
• Consumer, the threaded object that is consuming queue entries;
and
• PC, the tiny class that creates the single Q, Producer, and
Consumer.
Producer consumer problem
class Q
{
int n; synchronized void put(int n)
boolean valueSet = false; {
synchronized int get() if(valueSet)
{ try
if(!valueSet) {
try wait();
{ } catch(InterruptedException e)
wait(); {
System.out.println("InterruptedException caught");
} catch(InterruptedException e) }
{ this.n = n;
System.out.println("InterruptedException caught");
valueSet = true;
}
System.out.println("Put: " + n);
System.out.println("Got: " + n);
notify();
valueSet = false;
}
notify();
}
return n;
}
Producer consumer problem
class Producer implements Runnable
{ class Consumer implements Runnable
{
Q q;
Q q;
Producer(Q q)
Consumer(Q q)
{
{
this.q = q;
this.q = q;
new Thread(this, "Producer").start();
new Thread(this, "Consumer").start();
}
}
public void run() public void run()
{ {
int i = 0; while(true)
while(true) {
{ q.get();
q.put(i++); }
} }
} }
}
Producer consumer problem
class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Deadlock
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.
Thank You!!!

You might also like