Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views

Enterprise Java - Unit 2

The document discusses multithreading in Java. It covers topics like thread model, thread states, advantages of multithreading, differences between multitasking and multithreading. Exception handling in Java is also discussed including try-catch, throw, throws and custom exceptions.

Uploaded by

Charan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Enterprise Java - Unit 2

The document discusses multithreading in Java. It covers topics like thread model, thread states, advantages of multithreading, differences between multitasking and multithreading. Exception handling in Java is also discussed including try-catch, throw, throws and custom exceptions.

Uploaded by

Charan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

ENTERPRISE JAVA

(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

4) int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Java try-catch block
➢ Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
➢ If an exception occurs at the particular statement of try block, the rest of the block code
will not execute. So, it is recommended not to keeping the code in try block that will not
throw an exception.
➢ Java try block must be followed by either catch or finally block.
Internal working of java try-catch block

Default exception handler


Java try-catch block

Problem without exception handling Solution by exception handling

Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero

The rest of the code is not executed


(in such case, the rest of the code
statement is not printed). Output:
Java try-catch block

Resolving the exception in a catch block.

Output:
Java catch multiple exceptions

➢ A try block can be followed by one or more catch blocks.


➢ Each catch block must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-catch block.
➢ At a time only one exception occurs and at a time only one catch block is executed.
➢ All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
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

Java finally block is always executed whether


exception is handled or not.

Java finally block follows try or catch block.

If you don't handle exception, before terminating the


program, JVM executes finally block(if any).

Finally block in java can be used to put "cleanup"


code such as closing a file, closing connection etc.

For each try block there can be zero or more catch


blocks, but only one finally block.

The finally block will not be executed if program


exits(either by calling System.exit() or by causing a
fatal error that causes the process to abort).
Different cases where java finally block can be used

Case 1: where exception doesn't occur.

Output:
Different cases where java finally block can be used

Case 2: where exception occurs and not handled.

Output:
Different cases where java finally block can be used

Case 3: where exception occurs and handled.

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.

Syntax: throw exception;

Example: throw new IOException("sorry device error);


Java throw 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.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent

2) You can perform many operations together, so it saves time.

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:

Process-based Multitasking (Multiprocessing) Thread-based Multitasking (Multithreading)

➢ 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.

Threads are independent. If there occurs exception in one


thread, it doesn't affect other threads. It uses a shared
memory area.

As shown in the above figure, a thread is executed inside


the process. There is context-switching between the
threads. There can be multiple processes inside the OS,
and one process can have multiple threads.
Life cycle of a Thread (Thread States)

The life cycle of the thread


in java is controlled by JVM.

The java thread states are


as follows:

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

How to control Main thread


➢ To control main thread, we must obtain a reference to it.

➢ 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.

Commonly used Constructors of Thread class:


Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Implementing the 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.

Run Method Syntax: public void run()

➢ 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:

➢ A new thread starts(with new callstack).


➢ The thread moves from New state to the Runnable state.
➢ When the thread gets a chance to execute, its target run() method will run.
Implementing the Runnable Interface

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:

If you are implementing


Runnable interface in your
class, then you need to
explicitly create a Thread
class object and need to
pass the Runnable interface
implemented class object as
a parameter in its Output:
constructor.
Extending Thread class

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 :

1. Declare the class as extending the Thread class.


2. Implement the run() method.
3. Create a thread object.
4. Call the thread’s start() method to initiate the thread execution.
Extending Thread class

In this case also, we must


override the run() and then use
the start() method to run the
thread.
Also, when you create
MyThread class object, Thread
class constructor will also be
invoked, as it is the super
class, hence MyThread class
Output:
object acts as Thread class
object.
Extending Thread class

Some Important points to Remember

➢ 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 :

final boolean isAlive( ) final void join( ) throws InterruptedException

Return Value:
Returns true if the thread upon
which it is called is still running.

It returns false otherwise.


isAlive() and join() methods of Thread Class

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.

The synchronization is mainly used to

➢ To prevent thread interference.


➢ To prevent consistency problem.
Synchronization
Why we need Syncronization?

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.

2. Cooperation (Inter-thread communication)


It is all about allowing synchronized threads to communicate with each other.
Understanding the problem without Synchronization

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.

Q) Which is more preferred - Synchronized method or Synchronized block?


Inter-thread Communication
➢ Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
➢ Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.
➢ It is implemented by following methods of Object class:

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():

public final void wait()throws InterruptedException

public final void wait(long timeout) throws InterruptedException

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()

You might also like