Java Unit-3
Java Unit-3
Exception:
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is
why we need to handle exceptions.
Types of Exceptions:
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, there are three types of exceptions
namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that directly inherit the Throwable class except Runtime Exception and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the Runtime Exception are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error
Error vs Exception:
Basis of comparison Exception Error
Recoverable/ Exception can be recovered by An error cannot be recovered.
Irrecoverable using the try-catch block.
Type It can be classified into two All error in JAVA are unchecked.
categories i.e. checked and
unchecked
Occurrence It occurs at compile time or run It occurs at run time.
time
Package It belongs to java.lang.Exception It belongs to java.lang.Error package.
package
Known or Unknown Only checked exceptions are Errors will not be known to the compiler.
known to the compiler.
Causes It is mainly caused by the It is mostly caused by the environment in
application itself. which the application is running.
Example Checked Exception; java.lang.StackOverFlow,
Unchecked Exception:
ArrayIndexOutOfBound Exception,
NullPointer Exception,
Arithematic Exception.
TRY:
SYNTAX:
Try
{
-------
-------
-------
}
//Example program :
Import java.lang.*;
class Execute
{
public static void main(String[] args)
{
int x=10;y=0;z;
try
{
z=x/y ; //divide by zero which is infinety
System.out.println(z);
}
catch(arthimeticexception e)
{
system.out.println(“division is not possible “);
}
system.out.println(“program over”);
}
}
CATCH:
if there is an exception in try block then only catch block will be executed. If no exception in try
block, it doesn’t catch in catch block.
SYNTAX:
Catch
{
-------
-------
-------
}
if there exception in try block then only catch block will executed
if exception doesn’t occur in try block, then it does not catch in catch block
THROW:
SYNTAX:
throw new exceptiontype(“content”);
>throw is a keyword
>and the exception type (ex arthithematic or array out of bound etc)
Import java.lang.*;
Class Robo
{
public static void main(String[] args);
{
try
{
throw new arthimeticException(“this is my own exception”);
}
catch(airtimeticException e)
{
System.out.println(e.getmessage());
}
System.out.println(“program over”);
}
output:
this is my own exception
Program over
THROWS:
It is a keyword used when we doesn’t want to handle the exception and try to send the exception to the
jvm or caller.
SYNTAX:
_____________
_____________
Import java.lang.*;
Class Test
{
public static void main(String[] args)throws exception
{
Thread.sleep(2000);
System.out.println(“demo on throws”);
}
}
Explanation of the above program
>output will be in 2000miliseconds(i.e 2 secs). then thread will be in waiting state and prints
demo on throws
>if we don’t handle the sleep method it generates compile time error.
FINALLY:
The ‘finally’ block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
It is the keyword used to create a block of code that will be executed after a try/catch
block whether the exception is handled or not.
If exception occurs catch block executes and then finally block is executed.
If no exception, then finally block will be executed.
It should be written after try block or catch block.
//program for finally block
Import java.lang.*;
class Robo
{
public static void main(Sting args [])
{
try
{
Int x, y, res;
X=10;
Y=0;
res = x/y;
System.out.println(res);
}
catch(ArithematicException e)
{
System.out.println(“Division by zero is not possible ”);
}
finally
{
System.out.println(“Hi! This is final block”);
}
System.out.println(“Program ends”);
}
There are various stages in life cycle of thread as shown in the figure.
1. New
2. Runnable
3. Running
4. Waiting
5. Dead
New: In this phase, the thread is created using class “Thread class”. It remains in
this state till the program starts the thread. It is known as born thread.
Runnable: In this page, 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.
Running: When the thread starts executing, then the state is changed to
“running” state. The scheduler selects one thread from thread pool and it starts
executing in the application.
Waiting: This is the state when a thread has to wait. As the multiple threads are
running in the application, there is no need for synchronization between threads.
Hence, one thread has to wait till the other thread gets executed. Therefore, the
state is referred as waiting state.
Dead: 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”.
The JAVA contains a built-in class Thread inside java.lang package. The Thread
contains all the methods that are related to threads.
To create a thread using Thread class, follow the steps given below:
Step-1: Create a class as a child of Thread class. That means, create a class to
extend Thread class.
Step-2: Override the run () method with the code that is to be executed by thread.
The run () method must be public while overriding.
Step-3: Create the object of the newly created class in the main () method.
Step-4: Call the start () method on the object created in the above step.
Example:
Synchronized keyword:
The process of allowing only a single thread to access the shared data or resource at a
particular point of time is known as Synchronization.
Need of synchronization.
If the data is keep on updating by threads we should go for synchronization.
We need synchronization keyword.
Synchronization is applied on methods blocks
We cant apply synchronization on variables and class.
Synchronization is developed locking mechanism locking mechanism taken care by jvm.
As Java is a multi-threaded language, it supports a very important concept of Synchronization.
This method helps us to protect the data from the access by multiple threads.
Java provides the mechanism of synchronization using the synchronized blocks.
We declare all synchronized blocks in Java by using a synchronized keyword. A block that is
declared with a synchronized keyword ensures that only a single thread executes .
IMP POINTS:
Synchronization is a technique through which we can control multiple thread or among the
number of threads only one thread will enter inside synchronisaton area the main purpose of
synchronization area.
The main purpose of synchronization is to overcome the problem of multithreading when
threads are trying to access same resource
By using synchronized keyword , only thread enter into the loop after its work done , the second
will enter and so on, synchronized keyword will limit the access of three threads entering into
loop.
SYNCHRONISATION IS CLASSIFIED INTO :
METHOD LEVEL SYNCHRONISATION AND BLOCK LEVEL SYNCHRONISATION.
________ code;
t1.start();
t2.start();
t3.start();
here t1,t2,t3 are trying to access same resource so these is waiting problem and three threads at a
time enter into the same resource,To avoid this problem we have to use synchronized keyword.
{
------some code------
T1.start();
T2.start();
T3.start();
By using synchronized keyword,only one thread enter into the loop after its work done,the second
thread will enter and so on..
Synchronized keyword will limit the access of three threads entering into the loop.
..
Sychronisation(this)
{
//some code
t1.start();
t2.start.();
t3.start();
Syntax:
synchronized( lockObject )
{
// synchronized statements
}
How to Avoid Deadlock in Java
In Java, deadlock is a part of multithreading. The multithreading environment allows us to run
multiple threads simultaneously for multitasking.
Sometimes the threads find themselves in the waiting state, forever that is a deadlock situation.
The deadlock is a situation when two or more threads try to access the same object that is acquired
by another thread. Since the threads wait for releasing the object, the condition is known as
deadlock.The situation arises with more than two threads.
What is Deadlock :
In the thread, each object has a lock. To acquire a lock, Java provides synchronization to lock a method or
code block. It allows that at a time only one thread can access that method.
Nevertheless, if a thread wants to execute a synchronized method it first tries to acquire a lock. It is
possible that another thread has already acquired that lock then the thread (that wants to acquire the lock)
will have to wait until the previous thread does not release the lock.
Let’s understand this with an example;
Suppose, there are two threads A and B. The thread A and B acquired the lock of Object-A and Object-
B, respectively. Assume that thread A executing method A and wants to acquire the lock on Object-B,
while thread B is already acquired a lock on Object-B.
On the other hand, thread B also tries to acquire a lock on Object-A, while thread A is acquired a lock
on Object-A. In such a situation both threads will not complete their execution and wait for releasing
the lock. The situation is known as, deadlock.
o First, we look and understand the code if we found nested synchronized block or trying to get a lock
on a different object or calling a synchronized method from other synchronized method, these reason
leads to a deadlock situation.
o Another way to detect deadlock is to use the io portal. It allows us to upload a thread dump and
analyze it.
o We can also use jConsole or VisualVM to detect deadlock. It shows us which threads are getting
locked and on which object.
In the above example, there are two threads that are attempting to transfer money to each other at the
same time. It creates a deadlock situation because the threads try to acquire the lock in the reverse order.
o Avoid Unnecessary Locks: We should use locks only for those members on which it is required.
Unnecessary use of locks leads to a deadlock situation. We recommend you to use a lock-free data
structure. If possible, keep your code free form locks. For example, instead of using synchronized
ArrayList use the ConcurrentLinkedQueue.
o Avoid Nested Locks: Another way to avoid deadlock is to avoid giving a lock to multiple threads if we
have already provided a lock to one thread. Since we must avoid allocating a lock to multiple threads.
o Using Thread.join() Method: You can get a deadlock if two threads are waiting for each other to
finish indefinitely using thread join. If your thread has to wait for another thread to finish, it's always
best to use join with the maximum time you want to wait for the thread to finish.
o Use Lock Ordering: Always assign a numeric value to each lock. Before acquiring the lock with a
higher numeric value, acquire the locks with a lower numeric value.
o Lock Time-out: We can also specify the time for a thread to acquire a lock. If a thread does not
acquire a lock, the thread must wait for a specific time before retrying to acquire a lock.