Enterprise Java - Unit 2
Enterprise Java - Unit 2
(20MCA202)
BY
Anantha Murthy
Assistant Professor
Dept. of MCA
NMAM.I.T, Nitte
Unit 2
1. Exceptions
Exception Handling
➢ The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
➢ Exception is an abnormal condition.
➢ Exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
➢ Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed. That
is why we use exception handling in Java.
Hierarchy of Java Exception classes
Hierarchy of Java Exception classes
Types of Java Exceptions
Types of Java Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known
as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Common Scenarios of Java Exceptions
1) int a=50/0;//ArithmeticException
2) String s=null;
System.out.println(s.length());//NullPointerException
3) String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
Output:
Java catch multiple exceptions
Output:
Java catch multiple exceptions
Output:
Compile-time error
Java Nested try block
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Java Nested try block
Output:
Java finally block
Output:
Different cases where java finally block can be used
Output:
Different cases where java finally block can be used
Output:
Java throw Keyword
➢ The Java throw keyword is used to explicitly throw an exception.
➢ We can throw either checked or uncheked exception in java by throw keyword.
➢ The throw keyword is mainly used to throw custom exception.
Output:
Stack Trace
Java throws keyword
➢ The throws keyword indicates what exception type may be thrown by a method.
➢ The Java throws keyword is used to declare an exception.
➢ It gives an information to the programmer that there may occur an exception so it is better
for the programmer to provide the exception handling code so that normal flow can be
maintained.
➢ Exception Handling is mainly used to handle the checked exceptions.
Bcoz....
1. unchecked Exception: under your control so correct your code.
2. error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
➢ If there occurs any unchecked exception such as NullPointerException, it is programmers
fault that he is not performing check up before the code being used.
Java throws keyword
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
Output:
Differences between throw and throws
Java Custom Exception
➢ If you are creating your own Exception that is known as custom exception or user-defined
exception.
➢ Java custom exceptions are used to customize the exception according to user need.
➢ Java provides us facility to create our own exceptions which are basically derived classes of
Exception.
Exception class with super() Exception class without super()
We pass the string to the constructor of the super class- Exception which is obtained using
“getMessage()” function on the object created.
Java Custom Exception
Output: Output:
Unit 2
2.Multithreaded
Programming
Multithreading
➢ Multithreading in Java is a process of executing multiple threads simultaneously.
➢ A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
➢ However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
3) Since Threads are independent, it doesn't affect other threads if an exception occurs in a
single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:
➢ Each process has an address in memory. In ➢ Threads share the same address space.
other words, each process allocates a ➢ A thread is lightweight.
separate memory area. ➢ Cost of communication between the
➢ A process is heavyweight. thread is low.
➢ Cost of communication between the ➢ Inter-thread communication is less
process is high. expensive compared to inter-process
➢ Switching from one process to another communication.
requires some time for saving and loading
registers, memory maps, updating lists, etc.
Java Thread Model
A thread is a lightweight subprocess, the smallest unit of
processing. It is a separate path of execution.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Life cycle of a Thread (Thread States)
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Main thread in Java
When a Java program starts up, one thread begins running immediately. This is usually called
the main thread of program, because it is the one that is executed when program begins.
Properties :
● 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
➢ This can be done by calling the method currentThread( ) which is present in Thread class.
This method returns a reference to the thread on which it is called.
Main thread in Java
Main thread Example
Output:
Java Thread class
➢ Java provides Thread class to achieve thread programming.
➢ Thread class provides constructors and methods to create and perform operations on a
thread.
➢ Thread class extends Object class and implements Runnable interface.
Java Thread class Methods
Java Thread class Methods
How to create thread
There are two ways to create a thread:
➢ By implementing Runnable interface.
➢ By extending Thread class.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
The easiest way to create a thread is to create a class that implements the runnable interface.
After implementing runnable interface, the class needs to implement the run() method.
➢ It introduces a concurrent thread into your program. This thread will end when run() method
terminates.
➢ You must specify the code that your thread will execute inside run() method.
➢ run() method can call other methods, can use other classes and declare variables just like y
other normal method.
Implementing the Runnable Interface
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run() and is
used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
Steps :
1. Declare the class as implementing Runnable interface.
2. Implement the run() method.
3. Create a thread by defining an object that is instantiated from the runnable interface
implemented class as the target of the thread.
4. Call the thread’s start() method to run the thread.
Eg:
Mythread m=new Mythread();
Thread T=new Thread(m); Or new Thread(new Mythread()).start();
T.start();
Implementing the Runnable Interface
Note:
This is another way to create a thread by a new class that extends Thread class and create an
instance of that class.
The extending class must override run() method which is the entry point of new thread.
Steps :
➢ When we extend Thread class, we cannot override setName() and getName() functions,
because they are declared final in Thread class.
➢ While using sleep(), always handle the exception it throws.
static void sleep(long milliseconds) throws InterruptedException
Questions :
1. What if we call run() method directly without using start() method?
2. Can we Start a thread twice?
isAlive() and join() methods of Thread Class
Q) How can one thread know when another thread has ended?
A) Java multi-threading provides two ways to find that
1) isAlive() 2) join()
Syntax : Syntax :
Return Value:
Returns true if the thread upon
which it is called is still running.
isAlive() :
➢ It tests if this thread is alive.
➢ A thread is alive if it has been started and has not yet died.
➢ There is a transitional period from when a thread is running to when a thread is not running.
After the run() method returns, there is a short period of time before the thread stops.
➢ If we want to know if the start method of the thread has been called or if thread has been
terminated, we must use isAlive() method.
➢ This method is used to find out if a thread has actually been started and has yet not
terminated.
isAlive() and join() methods of Thread Class
join() :
➢ When the join() method is called, the current thread will simply wait until the thread it is
joining with is no longer alive.
➢ Or we can say the method that you will more commonly use to wait for a thread to finish is
called join( ).
➢ This method waits until the thread on which it is called terminates.
➢ Its name comes from the concept of the calling thread waiting until the specified thread joins
it.
➢ Additional forms of join( ) allow you to specify a maximum amount of time that you want to
wait for the specified thread to terminate.
Syntax: final void join(long milliseconds) throws InterruptedException
isAlive() and join() methods of Thread Class
isAlive() and join() methods of Thread Class
Output:
Output:
Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
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.
Types of Thread Synchronization
There are two types of thread synchronization.
1. Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
a. Synchronized method.
b. Synchronized block.
Output:
Java synchronized method
➢ If you declare any method as synchronized, it is known as synchronized method.
➢ Synchronized method is used to lock an object for any shared resource.
➢ When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
➢ Syntax :
synchronized method_header
{
// Block of code
}
Understanding the problem with Synchronized method
Output:
Using Synchronized block
➢ If want to synchronize access to an object of a class or only a part of a method to be
synchronized then we can use synchronized block for it.
➢ It is capable to make any part of the object and method synchronized.
➢ Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines,
you can use synchronized block.
➢ If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
➢ Syntax:
synchronized (object)
{
// statements to be synchronized
}
Using Synchronized block
Output:
Difference between synchronized keyword and synchronized block
When we use synchronized keyword with a method, it acquires a lock in the object for the
whole method. It means that no other thread can use any synchronized method until the
current thread, which has invoked it's synchronized method, has finished its execution.
synchronized block acquires a lock in the object only between parentheses after the
synchronized keyword. This means that no other thread can acquire a lock on the locked
object until the synchronized block exits. But other threads can access the rest of the code of
the method.
wait() : tells calling thread to give up monitor and go to sleep until some other thread enters the
same monitor and call notify.
notify(): wakes up a thread that called wait() on same object.
notifyAll(): wakes up all the thread that called wait() on same object.
All the three method can be called only from within a synchronized context
Inter-thread Communication
Syntaxes :
wait():
notify():
public final void notify()
notifyAll():
public final void notifyAll()
Understanding the process of inter-thread communication
Inter-thread Communication
Output:
Differences between wait() and sleep()