0% found this document useful (0 votes)
2 views16 pages

oops unit 2

Java exceptions are events that disrupt the normal flow of program execution, and exception handling is a mechanism to manage runtime errors effectively. It involves using keywords like try, catch, and finally to maintain the application's flow and prevent crashes. Java also categorizes exceptions into checked and unchecked types, allowing developers to create robust applications by handling errors gracefully.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

oops unit 2

Java exceptions are events that disrupt the normal flow of program execution, and exception handling is a mechanism to manage runtime errors effectively. It involves using keywords like try, catch, and finally to maintain the application's flow and prevent crashes. Java also categorizes exceptions into checked and unchecked types, allowing developers to create robust applications by handling errors gracefully.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Java Exception

An exception in Java is an event that disrupts the normal flow of the program's Exception handling in Java is an effective mechanism for managing runtime errors
execution. It's a way for the program to signal that something unexpected or erroneous to ensure the application’s regular flow is maintained. Some Common examples of
has occurred. When an exception occurs, the normal sequence of instructions is exceptions include ClassNotFoundException, IOException, SQLException,
interrupted, and the program attempts to find an appropriate handler to deal with the RemoteException, etc. By handling these exceptions, Java enables developers to
situation. create robust and fault-tolerant applications.

Java Exception Handling


Example: The below Java program modifies the previous example to handle
Exception handling in Java allows developers to manage runtime errors effectively an ArithmeticException using try-catch, and finally blocks and keepsto the
by using mechanisms like try-catch block, finally block, throwing program running.
Exceptions, Custom Exception handling, etc. // Java program to demonstrates handling
// the exception using try-catch block
An Exception is an unwanted or unexpected event that occurs during the execution import java.io.*;
of a program (i.e., at runtime) and disrupts the normal flow of the program’s
instructions. It occurs when something unexpected happens, like accessing an class Gks {
invalid index, dividing by zero, or trying to open a file that does not exist. public static void main(String[] args)
Exception in Java is an error condition that occurs when something wrong happens {
during the program execution. int n = 10;
int m = 0;
Example: Showing an Arithmetic Exception or you can say divide by zero
exception. try {
import java.io.*;
// Code that may throw an exception
class Gks { int ans = n / m;
public static void main(String[] args) System.out.println("Answer: " + ans);
{ }
int n = 10; catch (ArithmeticException e) {
int m = 0;
// Handling the exception
int ans = n / m; System.out.println(
"Error: Division by zero is not allowed!");
System.out.println("Answer: " + ans); }
} finally {
} System.out.println(
"Program continues after handling the exception.");
}
}
}

Output
Note: When an exception occurs and is not handled, the program terminates
abruptly and the code after it, will never execute. Error: Division by zero is not allowed!
Program continues after handling the exception.
Exception Handling in Java
Note: With the help of exception handling we can detect and handle the exceptions
gracefully so that the normal flow of the program can be maintained.
Note: The finally block always executes, even if no exception occurs, making it a
reliable place for cleanup operations.
The summary is depicted via visual aid below as follows:

Java Exception Hierarchy


All exception and error types are subclasses of the class Throwable, which is the
base class of the hierarchy. One branch is headed by Exception. This class is used
for exceptional conditions that user programs should catch. NullPointerException is
an example of such an exception. Another branch, Error is used by the Java run-
time system(JVM) to indicate errors having to do with the run-time environment
itself(JRE). StackOverflowError is an example of such an error.

The below figure demonstrates the exception hierarchy in Java:


Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of the
programmer, and we should not try to handle errors.

Difference Between Exception and Error

Aspect Error Exception

An Error indicates a serious


Exception indicates conditions
problem that a reasonable
that a reasonable application
application should not try to
might try to catch
Definition catch.
The unchecked exceptions are just opposite to the checked exceptions. The compiler
Caused by conditions in the will not check these exceptions at compile time. In simple words, if a program
Caused by issues with the JVM
program such as invalid input throws an unchecked exception, and even if we didn’t handle or declare it, the
or hardware.
Cause or logic errors. program would not give a compilation error. Examples of Unchecked Exception are
listed below:
OutOfMemoryError IOException 1. ArithmeticException: It is thrown when there’s an illegal math operation.
StackOverFlowError NullPointerException 1. ClassCastException: It is thrown when you try to cast an object to a class it
Examples
does not belongThis to.
To know more differences between Exception and Errors, refer to this 1. NullPointerException: It is thrown when you try to use a null object (e.g.
article: Exception vs Errors in Java. accessing its methods or fields)
1. ArrayIndexOutOfBoundsException: ThisThis occurs when we try to access an
Types of Java Exceptions array element with an invalid index.
Java defines several types of exceptions that relate to its various class libraries. Java 1. ArrayStoreException: Thishandle happens when you store an object of the
also allows users to define their it’sexceptions. wrong type in an array.
1. IllegalThreadStateException: It is thrown when a thread operation is not
allowed in its current state
Exceptions can be categorized in two ways:
1. Built-in Exceptions Note: For checked vs unchecked exception, see Checked vs Unchecked Exceptions

 Checked Exception 2. User-Defined Exception


 Unchecked Exception
1. User-Defined Exceptions Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called “user-
1. Built-in Exception defined Exceptions“.
Build-in Exception are pre-defined exception classes provided by Java to handle
common errors during program execution. Methods to Print the Exception Information

1.1 Checked Exceptions


Checked exceptions are called compile-time exceptions because these exceptions are Method Description
checked at compile-time by the compiler. Examples of Checked Exception are listed
below:
1. ClassNotFoundException: Throws when the program tries to load a class at Prints the full stack trace of the
runtime but the class is not found because it’sbelong not present in the correct exception, including the name,
location or it is missing from the project. printStackTrace() message, and location of the error.
1. InterruptedException: Thrown when a thread is paused and another thread
interrupts it. Prints exception information in
1. IOException: Throws when input/output operation fails the format of the Name of the
1. InstantiationException: Thrown when the program tries to create an object of a toString() exception.
class but fails because the class is abstract, an interface, or has no default
constructor. Prints the description of the
1. SQLException: Throws when there’s an error with the database. exception.
1. FileNotFoundException: Thrown when the program tries to open a file that getMessage()
doesn’t exist

1.2 Unchecked Exceptions


What is Java Exception Handling and Why is it Important?

Java Exception Handling is a mechanism to handle runtime errors, allowing a program finally {
to continue operating or terminate gracefully. It separates error-handling code from // cleanup code
regular code, enhancing readability and maintainability. Without proper exception }
handling, an error can cause the entire application to crash, leading to a poor user
experience.

Mechanics of Exception Handling


4.throw: The throw keyword is used to explicitly throw an exception.

Java provides a structured way to handle exceptions using five key keywords: try,
catch, finally, throw, and throws. throw new IOException("File not found");

1. try: The try block contains code that might throw an exception. If an exception
occurs within this block, the control is transferred to the corresponding catch block.
5. throws: The throws keyword is used in the method signature to declare that the
method might throw exceptions.
try {
// code that may throw an exception
} catch (ExceptionType e) { public void readFile() throws IOException {
// code to handle the exception // method code
} }

2. catch: The catch block is used to handle the exception thrown by the try block.
Multiple catch blocks can be used to handle different types of exceptions. Try-Catch Block
A try-catch block in Java is a mechanism to handle exception. The try block contains
code that might thrown an exception and the catch block is used to handle the
catch (IOException e) { exceptions if it occurs.
// handle IOException try {
} catch (SQLException e) { // Code that may throw an exception
// handle SQLException } catch (ExceptionType e) {
} // Code to handle the exception
}

finally Block
The finally Block is used to execute important code regardless of whether an
3. finally: The finally block contains code that will always execute, regardless of exception occurs or not.
whether an exception was thrown or not. It is typically used for cleanup activities, such Note: finally block is always executes after the try-catch block. It is also used for
as closing files or releasing resources. resource cleanup.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}finally{
// cleanup code
}

Handling Multiple Exception


We can handle multiple type of exceptions in Java by using multiple catch blocks,
each catching a different type of exception.
try {
// Code that may throw an exception
} catch (ArithmeticException e) {
// Code to handle the exception
} catch(ArrayIndexOutOfBoundsException e){
//Code to handle the anothert exception
}catch(NumberFormatException e){
//Code to handle the anothert exception
} Illustration:
class Gks{
How Does JVM Handle an Exception?
Default Exception Handling: When an Exception occurs, the JVM Creates an public static void main(String args[])
exception object containing the error name, description, and program state. Creating {
the Exception Object and handling it in the run-time system is called throwing an // Taking an empty string
Exception. There might be a list of the methods that had been called to get to the String s = null;
method where an exception occurred. This ordered list of methods is called Call
Stack. Now the following procedure will happen. // Getting length of a string
1. The run-time system searches the call stack for an Exception handler System.out.println(s.length());
1. It starts searching from the method where the exception occurred and proceeds }
backward through the call stack. }
1. If a handler is found, the exception is passed to it. Output:
1. If no handler is found, the default exception handler terminates the program and
prints the stack trace.
Exception in thread “abc” Name of Exception : Description
… …… .. // Call Stack
Look at the below diagram to understand the flow of the call stack.

Let us see an example that illustrates how a run-time system searches for appropriate
exception handling code on the call stack.
Example:
// Class
// ExceptionThrown
class Gks {

// It throws the Exception(ArithmeticException)


// Appropriate Exception handler is not found try {
// within this method int i = computeDivision(a, b);
static int divideByZero(int a, int b) }
{
// Catch block to handle ArithmeticException
// this statement will cause ArithmeticException // exceptions
// (/by zero) catch (ArithmeticException ex) {
int i = a / b;
// getMessage() will print description
return i; // of exception(here / by zero)
} System.out.println(ex.getMessage());
}
// The runTime System searches the appropriate }
// Exception handler in method also but couldn't have }
// found. So looking forward on the call stack
static int computeDivision(int a, int b) Output
{
/ by zero
int res = 0;

// Try block to check for exceptions How Programmer Handle an Exception?


try { Customized Exception Handling: Java exception handling uses five keywords: try,
catch, throw and throws, and finally. Code that might cause an exception goes in the
res = divide By Zero(a, b); try block. If an exception occurs, it is caught using catch. We can throw exceptions
} manually with throw, and methods must declare exceptions they can throw using
throws. The finally block is used for code that must run after try, whether an
// Catch block to handle NumberFormatException exception occurs or not.
// exception doesn't matches with Tip: One must go through control flow in try catch finally block for better
// ArithmeticException understanding.
catch (NumberFormatException ex) { Need for try-catch clause (Customized Exception Handling)
Consider the below program in order to get a better understanding of the try-catch
System.out.println( clause.
"NumberFormatException is occurred"); Example:
} // Java Program to Demonstrate
return res; // Need of try-catch Clause
} class Gks {

// Found appropriate Exception handler public static void main(String[] args) {


// i.e. matching catch block.
public static void main(String args[]) // Taking an array of size 4
{ int[] arr = new int[4];

int a = 1; // Now this statement will cause an exception


int b = 0; int i = arr[4];

// Try block to check for exceptions // This statement will never execute
// as above we caught with an exception Java throw
System.out.println("Hi, I want to execute"); 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 of throw in Java


throw and throws in Java throw Instance
Where instance is an object of type Throwable (or its subclasses, such as Exception).
throw new ArithmeticException("/ by zero");
In Java, Exception Handling is one of the effective means to handle runtime errors But this exception i.e., Instance must be of type Throwable or a subclass
so that the regular flow of the application can be preserved. It handles runtime errors of Throwable.
such as NullPointerException, ArrayIndexOutOfBoundsException, etc. To The flow of execution of the program stops immediately after the throw statement is
handle these errors effectively, Java provides two key concepts throw and throws. executed and the nearest enclosing try block is checked to see if it has
Difference Between throw and throws a catch statement that matches the type of exception. If it finds a match, controlled
The main differences between throw and throws in Java are follows: is transferred to that statement otherwise next enclosing try block is checked, and so
on. If no matching catch is found then the default exception handler will halt the
program.
Difference Between throw and throws
The main differences between throw and throws in Java are follows: Example 1:
Feature throw throws class Gks {
static void fun()
{
It is used to declare that a
It is used to explicitly throw an try {
method might throw one or
exception. throw new NullPointerException("demo");
Definition more exceptions.
}
catch (NullPointerException e) {
It is used inside a method or a It is used in the method System.out.println("Caught inside fun().");
Location block of code. signature. throw e; // rethrowing the exception
}
It is only used for checked }
It can throw both checked and exceptions. Unchecked
unchecked exceptions. exceptions do not public static void main(String args[])
require throws. {
Usage try {
fun();
The method’s caller is }
The method or block throws the
responsible for handling the catch (NullPointerException e) {
exception.
Responsibility exception. System.out.println("Caught in main.");
}
Stops the current flow of It forces the caller to handle }
Flow of
execution immediately. the declared exceptions. }
Execution

throw new public void myMethod() Output

Example ArithmeticException(“Error”); throws IOException {} Caught inside fun().


Caught in main. }
Output:
error: unreported exception InterruptedException; must be caught or declared to be
Explanation: The above example demonstrates the use of the throw keyword to
thrown
explicitly throw a NullPointerException. The exception is caught inside
the fun() method and rethrown, where it is then caught in the main() method.
Explanation: In the above program, we are getting compile time error because there
is a chance of exception if the main thread is going to sleep, other threads get the
Example 2:
chance to execute the main() method which will cause InterruptedException.
class Gks {
public static void main(String[] args)
Example 2: Using throws to Handle Exception
{
// Java program to illustrate throws
System.out.println(1 / 0);
class Gks {
}
public static void main(String[] args)
}
throws InterruptedException
Output:
{
Exception in thread "main" java.lang.ArithmeticException: / by zero
Thread.sleep(10000);
System.out.println("Hello Gks");
Java throws }
throws is a keyword in Java that is used in the signature of a method to indicate that }
this method might throw one of the listed type exceptions. The caller to these Output:
methods has to handle the exception using a try-catch block. Hello Gks

Syntax of Java throws Explanation: In the above program, by using the throws keyword we handled
type method_name(parameters) throws exception_list the InterruptedException and we will get the output as Hello Gks.
where, exception_list is a comma separated list of all the exceptions which a method
might throw. Example 3: Throwing an Exception with throws
In a program, if there is a chance of raising an exception then the compiler always class Gks {
warns us about it and compulsorily we should handle that checked exception,
Otherwise, we will get compile time error saying unreported exception XXX must static void fun() throws IllegalAccessException
be caught or declared to be thrown. To prevent this compile time error we can {
handle the exception in two ways: System.out.println("Inside fun(). ");
1. By using try catch throw new IllegalAccessException("demo");
1. By using the throws keyword }
We can use the throws keyword to delegate the responsibility of exception handling
to the caller (It may be a method or JVM) then the caller method is responsible to public static void main(String args[])
handle that exception. {
try {
Example 1: Unhandled Exception fun();
// Java program to illustrate error in case }
// of unhandled exception catch (IllegalAccessException e) {
class Gks { System.out.println("Caught in main.");
public static void main(String[] args) }
{ }
Thread.sleep(10000); }
System.out.println("Hello Gks");
} Output
Inside fun(). 3) System.err: standard error stream
Caught in main. Let's see the code to print output and an error message to the console.

Important Points to Remember 1. System.out.println("simple message");


2. System.err.println("error message");
 throws keyword is required only for checked exceptions and usage of the throws
keyword for unchecked exceptions is meaningless. Let's see the code to get input from console.
 throws keyword is required only to convince the compiler and usage of the
1. int i=System.in.read();//returns ASCII code of 1st character
throws keyword does not prevent abnormal termination of the program.
2. System.out.println((char)i);//will print the character
 With the help of the throws keyword, we can provide information to the caller of
the method about the exception. OutputStream Vs. InputStream
The explanation of OutputStream and InputStream classes are given below:
Java I/O
OutputStream
Java I/O (Input and Output) is used to process the input and produce the output. Java application uses an output stream to write data to a destination; it may be a file,
an array, peripheral device or socket.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations. InputStream
Java application uses an input stream to read data from a source; it may be a file, an
We can perform file handling in Java by Java I/O API. array, peripheral device or socket.

Core Concepts of Java I/O OutputStream Class


Java I/O revolves around two primary concepts: streams and readers/writers. OutputStream class is an abstract class. It is the superclass of all classes representing
an output stream of bytes. An output stream accepts output bytes and sends them to
Streams: Streams represent a sequence of data. In Java, there are two types of some sink.
streams: input streams and output streams. Input streams are used to read data from a
source, while output streams are used to write data to a destination. Streams can be Types of Stream
categorized into byte streams (InputStream and OutputStream) and character streams
(Reader and Writer).

Readers/Writers: Readers and writers are specialized stream classes designed for
handling character data. They provide a convenient way to read from and write to
character-based data sources. Readers read character data from input streams, while
writers write character data to output streams.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with
the console.

1) System.out: standard output stream

2) System.in: standard input stream


through cclasses that cease with the word "InputStream" or "OutputStream" of their
names,along with FileInputStream, BufferedInputStream, FileOutputStream and
BufferedOutputStream.

Byte streams offer a low-stage interface for studying and writing character bytes or
blocks of bytes. They are normally used for coping with non-textual statistics,
studying and writing files of their binary form, and running with network sockets.
Byte streams don't perform any individual encoding or deciphering. They treat the
data as a sequence of bytes and don't interpret it as characters.

Here are the some of the differences listed:


Aspect Character Streams Byte Streams

Data Handling Handle character-based data Handle raw binary data

Representation Classes end with "Reader" or Classes end with "InputStream


"Writer" or "OutputStream"

Java offers two types of streams:


Suitable for Textual data, strings, human- Non-textual data, binary files,
1. character streams readable info multimedia
2. Byte streams.

These streams can be different in how they are handling data and the type of data they
are handling. Character Encoding Automatic encoding and No encoding or decoding
decoding
1. Character Streams:
Character streams are designed to address character based records, which includes
textual records inclusive of letters, digits, symbols, and other characters. These Text vs non-Text data Text-based data, strings Binary data, images, audio,
streams are represented by way of training that quit with the phrase "Reader" or video
"Writer" of their names, inclusive of FileReader, BufferedReader, FileWriter, and
BufferedWriter.
Performance Additional conversion may Efficient for handling large
Character streams offer a convenient manner to read and write textual content- impact performance binary data
primarily based information due to the fact they mechanically manage character
encoding and decoding. They convert the individual statistics to and from the
underlying byte circulation the usage of a particular individual encoding, such as
Handle Large Text Files May impact performance due to Efficient, no encoding overhea
UTF-eight or ASCII.It makes person streams suitable for operating with textual
content files, analyzing and writing strings, and processing human-readable statistics. encoding

2. Byte Streams:
Byte streams are designed to deal with raw binary data, which includes all kinds of String Operations Convenient methods for string Not specifically designed for
data, including characters, pictues, audio, and video. These streams are represented operations string operations
Convenience Methods Higher-level abstractions for Low-level interface for byte Constructors:
 FileWriter(File file) – Constructs a FileWriter object given a File object.
text data data
 FileWriter (File file, boolean append) – constructs a FileWriter object given a
File object.
 FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with
Reading Line by Line Convenient methods for reading Byte-oriented, no built-in line a file descriptor.
lines reading methods  FileWriter (String fileName) – constructs a FileWriter object given a file name.
 FileWriter (String fileName, Boolean append) – Constructs a FileWriter object
given a file name with a Boolean indicating whether or not to append the data
File Handling Read/write text files Read/write binary files written.

Methods:
Network Communication Sending/receiving text data Sending/receiving binary data  public void write (int c) throws IOException – Writes a single character.
 public void write (char [] stir) throws IOException – Writes an array of
characters.
Handling Images/Audio/Video Not designed for handling Suitable for handling binary  public void write(String str)throws IOException – Writes a string.
 public void write(String str, int off, int len)throws IOException – Writes a
binary data directly multimedia data
portion of a string. Here off is offset from which to start writing characters and
len is the number of characters to write.
 public void flush() throws IOException flushes the stream
Text Encoding Supports various character No specific text encoding
 public void close() throws IOException flushes the stream first and then closes
encodings support the writer.
Reading and writing take place character by character, which increases the number
of I/O operations and affects the performance of the system.BufferedWriter can be
used along with FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter

File handling in Java using FileWriter and FileReader FileReader


FileReader is useful to read data in the form of characters from a ‘text’ file.
 This class inherited from the InputStreamReader Class.
Java FileWriter and FileReader classes are used to write and read data from text files  The constructors of this class assume that the default character encoding and the
(they are Character Stream classes). It is recommended not to use the default byte-buffer size are appropriate. To specify these values yourself,
FileInputStream and FileOutputStream classes if you have to read and write any construct an InputStreamReader on a FileInputStream.
textual information as these are Byte stream classes.
 FileReader is meant for reading streams of characters. For reading streams of raw
FileWriter bytes, consider using a FileInputStream.
FileWriter is useful to create a file writing characters into it.
 This class inherits from the OutputStream class. Constructors:
 The constructors of this class assume that the default character encoding and the  FileReader(File file) – Creates a FileReader , given the File to read from
default byte-buffer size are acceptable. To specify these values yourself,  FileReader(FileDescripter fd) – Creates a new FileReader , given the
construct an OutputStreamWriter on a FileOutputStream. FileDescripter to read from
 FileReader(String fileName) – Creates a new FileReader , given the name of
 FileWriter is meant for writing streams of characters. For writing streams of raw the file to read from
bytes, consider using a FileOutputStream.
 FileWriter creates the output file if it is not present already. Methods:
 public int read () throws IOException – Reads a single character. This method public void run() {
will block until a character is available, an I/O error occurs, or the end of the
stream is reached. System.out.println("This code is running in a thread");
 public int read(char[] cbuff) throws IOException – Reads characters into an
array. This method will block until some input is available, an I/O error occurs, }
or the end of the stream is reached. }
 public abstract int read(char[] buff, int off, int len) throws IOException
–Reads characters into a portion of an array. This method will block until some Another way to create a thread is to implement the Runnable interface:
input is available, an I/O error occurs, or the end of the stream is reached.
Parameters: Implement Syntax
cbuf – Destination buffer
off – Offset at which to start storing characters public class Main implements Runnable {
len – Maximum number of characters to read
public void run() {
 public void close() throws IOException closes the reader.
 public long skip(long n) throws IOException –Skips characters. This method System.out.println("This code is running in a thread");
will block until some characters are available, an I/O error occurs, or the end of
the stream is reached. }
Parameters:
}
n – The number of characters to skip

Multithreading in Java
Running Threads

Multithreading is a Java feature that allows the concurrent execution of two or more If the class extends the Thread class, the thread can be run by creating an instance of
parts of a program for maximum utilization of the CPU. Each part of such a program the class and call its start() method:
is called a thread. So, threads are lightweight processes within a process.
Extend Example

Java Threads public class Main extends Thread {

public static void main(String[] args) {


Threads allows a program to operate more efficiently by doing multiple things at the
same time. Main thread = new Main();
Threads can be used to perform complicated tasks in the background without thread.start();
interrupting the main program.
System.out.println("This code is outside of the thread");
Creating a Thread
}
There are two ways to create a thread. public void run() {
It can be created by extending the Thread class and overriding its run() method: System.out.println("This code is running in a thread");
public class Main extends Thread { }
}  Use case: Multiple threads competing for CPU time to perform their tasks
concurrently.
If the class implements the Runnable interface, the thread can be run by passing an
instance of the class to a Thread object's constructor and then calling the 3. Running state
thread's start() method:
 Example: When a thread executes its code inside the run() method.
Implement Example
 Use case: A thread executing a complex computation or performing a time-
public class Main implements Runnable { consuming task.

public static void main(String[] args) { 4. Blocked state:

Main obj = new Main();  Example: When a thread tries to access a synchronized block or method, but
another thread already holds the lock.
Thread thread = new Thread(obj);
 Use case: Multiple threads accessing a shared resource can only be obtained by
thread.start(); a single Thread, such as a database or a file.

System.out.println("This code is outside of the thread"); Terminated: A thread reaches the termination state because of the following reasons:

} o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
public void run() { unhandled exception or segmentation fault.
System.out.println("This code is running in a thread");

The Life Cycle of Thread in Java – Thread State


In Java, the life cycle of Thread goes through various states. These states represent
different stages of execution. Here are examples of each stage of the life cycle of
Thread in Java with real-life use cases:
1. New (born) state

 Example: Creating a new thread using the Thread class constructor.


 Use case: Creating a new thread to perform a background task while the main
Thread continues with other operations

2. Runnable state

 Example: After calling the start() method on a thread, it enters the runnable Priorities in Threads
state.
Priorities in Threads in Java is a concept where each thread has a priority in Priority of running thread: 1
layman’s language one can say every object has priority here which is represented Priority of running thread: 5
by numbers ranging from 1 to 10, Priority of running thread: 10

Constant Description Synchronization in Java


public static int Sets the default priority for the Thread. Synchronization in Java is a critical concept in concurrent programming that ensures
NORM_PRIORITY (Priority: 5) multiple threads can interact with shared resources safely. In a nutshell,
synchronization prevents race conditions, where the outcome of operations depends
on the timing of thread execution. It is the capability to control the access of multiple
public static int Sets the Minimum Priority for the Thread.
threads to any shared resource. Synchronization is a better option where we want to
MIN_PRIORITY (Priority: 1)
allow only one thread to access the shared resource.

public static int Sets the Maximum Priority for the Thread. Synchronized Blocks in Java
MAX_PRIORITY (Priority: 10) Java provides a way to create threads and synchronise their tasks
using synchronized blocks.
A synchronized block in Java is synchronized on some object. Synchronized
blocks in Java are marked with the synchronized keyword. All synchronized blocks
class Test extends Thread{
synchronize on the same object and can only have one thread executed inside them
public void run(){
at a time. All other threads attempting to enter the synchronized block are blocked
System.out.println("Priority of running thread: " +
until the thread inside the synchronized block exits the block.
Thread.currentThread().getPriority());
}
} General Form of Synchronized Block
synchronized(sync_object)
public class ThreadPriorityExample { {
public static void main(String args[]){ // Access shared variables and other
//creating thread. // shared resources
Test thrd1 = new Test(); }
Test thrd2 = new Test(); This synchronization is implemented in Java with a concept called monitors or
Test thrd3 = new Test(); locks. Only one thread can own a monitor at a given time. When a thread acquires a
lock, it is said to have entered the monitor. All other threads attempting to enter the
//set thread priority. locked monitor will be suspended until the first thread exits the monitor.
thrd1.setPriority(Thread.MIN_PRIORITY);
thrd2.setPriority(Thread.NORM_PRIORITY); Types of Synchronization
thrd3.setPriority(Thread.MAX_PRIORITY); There are the following two types of synchronization:

//start the thread. 1. Process Synchronization


thrd1.start(); 2. Thread Synchronization
thrd2.start();
thrd3.start(); 1. Process Synchronization in Java
} Process Synchronization is a technique used to coordinate the execution of multiple
} processes. It ensures that the shared resources are safe and in order.
Output:
2.Thread Synchronization
Thread Synchronization is used to coordinate and ordering of the execution of the
threads in a multi-threaded program.
public final void wait()throws It waits until object is notified.
InterruptedException
There are two types of thread synchronization in Java: mutual exclusive and inter-
thread communication.
public final void wait(long timeout)throws It waits for the specified amount of time.
1. Mutual Exclusive InterruptedException
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2) notify() method
2. Cooperation (Inter-thread communication in Java)
The notify() method wakes up a single thread that is waiting on this object's monitor.
Mutual Exclusive If any threads are waiting on this object, one of them is chosen to be awakened. The
Mutual Exclusive helps keep threads from interfering with one another while sharing choice is arbitrary and occurs at the discretion of the implementation.
data. It can be achieved by using the following three ways:
Syntax:
1. By Using Synchronized Method
1. public final void notify()
2. By Using Synchronized Block
3. By Using Static Synchronization 3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:
Inter-thread Communication in Java
1. public final void notifyAll()
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other. Understanding the process of inter-thread communication

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:

o wait()
o notify()
o 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.
The point to point explanation of the above diagram is as follows:
Method Description
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state
of the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy