This document provides an overview of Java unit 2, which covers exception handling, multithreaded programming, and inter-thread communication. It defines key concepts like exceptions, exception types, try/catch/throw/throws keywords, thread priorities, synchronization, and wait/notify methods. Example code is provided to demonstrate exception handling, thread creation and communication between threads using wait/notify.
2. SYLLABUS
Exception Handling
Fundamentals exception types
Uncaught exceptions
Throw
Throws
Final
Built in exception
Creating your own exceptions
Multithreaded Programming:Fundamentals
3. Cont…
Java thread model:priorities
Synchronization
Messaging
Thread classes
Runable interface
Inter thread communication
Suspending
Resuming and stopping threads
4. Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that the normal flow of the application can be
maintained.
Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the
program.
It is an object which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
5. Fundamentals exception types
Exceptions can be categorized into two ways:
Built-in Exceptions
Checked Exception
Unchecked Exception
User-Defined Exceptions
Exceptions that are already available in Java libraries are referred to
as built-in exception.
These exceptions are able to define the error situation so that we can
understand the reason of getting this error.
It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
6.
7. Example
class UncheckedExceptionExample1 {
public static void main(String args[])
{
int postive = 35;
int zero = 0;
int result = positive/zero;
//Give Unchecked Exception here.
System.out.println(result);
}
}
8. Uncaught exceptions
In java, assume that, if we do not handle the exceptions in a program. In this
case, when an exception occurs in a particular function, then Java prints a
exception message with the help of uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the
compiler but automatically caught and handled by the Java built-in exception
handler.
Java programming language has a very strong exception handling mechanism.
It allow us to handle the exception use the keywords like try, catch, finally,
throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the
exception occurs and terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions.
9. Throw
The throw keyword in Java is used to explicitly throw an exception from a
method or any block of code.
We can throw either checked or unchecked exception.
The throw keyword is mainly used to throw custom exceptions.
Syntax in Java throw
throw Instance
Example:
throw new ArithmeticException("/ by zero");
10. Example
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15);
}
}
11. Throws
The throws keyword indicates what exception type may be thrown by a
method.
There are many exception types available in Java: ArithmeticException,
ClassNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc.
12. Example
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
14. final
The final keyword is a non-access modifier used for classes, attributes and
methods, which makes them non-changeable (impossible to inherit or
override).
The final keyword is useful when you want a variable to always store the
same value, like PI (3.14159...).
The final keyword is called a "modifier".
15. Final
public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // will generate an error
System.out.println(myObj.x);
}
}
17. Built in exception
Exceptions that are already available in Java libraries are referred to
as built-in exception.
These exceptions are able to define the error situation so that we can
understand the reason of getting this error.
It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
Checked Exception
Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler. The compiler
ensures whether the programmer handles the exception or not. The
programmer should have to handle the exception; otherwise, the system has
shown a compilation error.
18. Example
import java.io.*;
class CheckedExceptionExample {
public static void main(String args[]) {
FileInputStream file_data = null;
file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt");
int m;
while(( m = file_data.read() ) != -1) {
System.out.print((char)m);
}
file_data.close();
}
}
19. CONT……
In the above code, we are trying to read the Hello.txt file and display its data
or content on the screen. The program throws the following exceptions:
The FileInputStream(File filename) constructor throws
the FileNotFoundException that is checked exception.
The read() method of the FileInputStream class throws the IOException.
The close() method also throws the IOException.
20. Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions.
The compiler will not check these exceptions at compile time.
In simple words, if a program throws an unchecked exception, and even if we
didn't handle or declare it, the program would not give a compilation error.
Usually, it occurs when the user provides bad data during the interaction with
the program.
21. Creating your own exceptions
In Java, we can create our own exceptions that are derived classes of the
Exception class. Creating our own Exception is known as custom exception or
user-defined exception. Basically, Java custom exceptions are used to
customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the
Exception class.
public class WrongFileNameException extends Exception {
public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}
22. Multithreaded
Programming:Fundamentals
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.
Java Multithreading is mostly used in games, animation, etc.
23. Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
24. Java thread model:priorities
As we already know java being completely object-oriented works within
a multithreading environment in which thread scheduler assigns the processor
to a thread based on the priority of thread. Whenever we create a thread in
Java, it always has some priority assigned to it. Priority can either be given by
JVM while creating the thread or it can be given by the programmer
explicitly.
Priorities in threads is a concept where each thread is having a priority
which in layman’s language one can say every object is having priority here
which is represented by numbers ranging from 1 to 10.
The default priority is set to 5 as excepted.
Minimum priority is set to 1.
Maximum priority is set to 10.
25. Cont….
Here 3 constants are defined in it namely as follows:
public static int NORM_PRIORITY
public static int MIN_PRIORITY
public static int MAX_PRIORITY
Let us do discuss how to get and set priority of a thread in java.
public final int getPriority(): java.lang.Thread.getPriority() method returns
priority of given thread.
public final void setPriority(int newPriority): java.lang.Thread.setPriority()
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.
26. Synchronization
Synchronization in java is the capability to control the access of multiple
threads to any shared resource.
In the Multithreading concept, multiple threads try to access the shared
resources at a time to produce inconsistent results.
The synchronization is necessary for reliable communication between
threads.
Why we use Synchronization
Synchronization helps in preventing thread interference.
Synchronization helps to prevent concurrency problems.
27. Types of Synchronization
Synchronization is classified into two types
Process Synchronization
Thread Synchronization
Process Synchronization:
The process is nothing but a program under execution. It runs independently
isolated from another process. The resources like memory and CPU time, etc.
are allocated to the process by the operation System.
Thread Synchronization:
Thread synchronization is two types, they are:
28. Cont…..
1.Mutual Exclusive:
A Mutex or Mutual Exclusive helps only one thread to access the shared
resources. It won’t allow the accessing of shared resources at a time. It can
be achieved in the following ways.
Synchronized Method
Synchronized block
Static Synchronization
2. Cooperation (Inter Thread Communication in java)
29. Messaging
JMS (Java Message Service) is an API that provides the facility to create, send
and read messages. It provides loosely coupled, reliable and asynchronous
communication.
JMS is also known as a messaging service.
Messaging is a technique to communicate applications or software
components.
JMS is mainly used to send and receive message from one application to
another.
30. Requirement of JMS
Generally, user sends message to application. But, if we want to send
message from one application to another, we need to use JMS API.
Consider a scenario, one application A is running in INDIA and another
application B is running in USA. To send message from A application to B, we
need to use JMS.
Advantage of JMS
1) Asynchronous: To receive the message, client is not required to send
request. Message will arrive automatically to the client.
2) Reliable: It provides assurance that message is delivered.
31. Thread classes
Thread a line of execution within a program.
Each program can have multiple associated threads.
Each thread has a priority which is used by the thread scheduler to determine
which thread must run first.
Java provides a thread class that has various method calls in order to manage
the behavior of threads by providing constructors and methods to perform
operations on threads.
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
32. 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)
33. Commonly used methods of Thread
class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method
on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
34. 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().
public void run(): is used to perform action for a thread.
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the 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.
35. Example
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();
}
}
36. 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()
notify()
notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
38. 2) notify() method
The notify() method wakes up a single thread that is waiting on this object's
monitor. If any 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.
Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
39. Suspending
The suspend() method of thread class puts the thread from running to waiting
state.
This method is used if you want to stop the thread execution and start it
again when a certain event occurs.
This method allows a thread to temporarily cease execution.
The suspended thread can be resumed using the resume() method.
Syntax
public final void suspend()
40. Example
public class JavaSuspendExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);