0% found this document useful (0 votes)
1 views

m3 java

The document provides a comprehensive overview of Exception Handling in Java, detailing the types of exceptions, their hierarchy, and the mechanisms for handling them using keywords like try, catch, and finally. It explains the differences between checked and unchecked exceptions, as well as the advantages of using exception handling in programming. Additionally, it covers annotations in Java, including built-in and custom annotations, and their significance in providing metadata and ensuring code correctness.

Uploaded by

upadhyaydev29
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)
1 views

m3 java

The document provides a comprehensive overview of Exception Handling in Java, detailing the types of exceptions, their hierarchy, and the mechanisms for handling them using keywords like try, catch, and finally. It explains the differences between checked and unchecked exceptions, as well as the advantages of using exception handling in programming. Additionally, it covers annotations in Java, including built-in and custom annotations, and their significance in providing metadata and ensuring code correctness.

Uploaded by

upadhyaydev29
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/ 76

MODULE -3

Exception Handling in Java


1.Exception Handling
2.Advantage of Exception Handling
3.Hierarchy of Exception classes
4.Types of Exception
5.Exception Example
6.Scenarios where an exception may occur
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.

What is Exception in Java?


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.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Note:-
Throwable, Error, and Exception, are all defined in the java.lang package. This package is automatically imported into every
class file
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error. The hierarchy of Java Exception classes is given below:

Major reasons why an exception Occurs


Error
•Invalid user input
•Device failure
•Loss of network connection
•Physical limitations (out-of-disk memory)
•Code errors
•Out of bound
•Null reference
•Type mismatch
•Opening an unavailable file
•Database errors
•Arithmetic errors
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
1.Checked Exception
2.Unchecked Exception
3.Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
Advertisement
2) Unchecked Exception
The classes that inherit the RuntimeException 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
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion,
assertion error etc. Errors are usually beyond the control of the programmer, and we should not
try to handle errors. Note:-Assertion is a statement in java. It can be
used to test your assumptions about the program.
While executing assertion, it is believed to be true.
If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing
•Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler.

•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.
Difference between Error and Exception
Let us discuss the most important part which is the differences between Error and
Exception that is as follows:
•Error: An Error indicates a serious problem that a reasonable application should not
try to catch.
•Exception: Exception indicates conditions that a reasonable application might try to
catch.

The advantages of Exception Handling in Java are as follows:


1.Provision to Complete Program Execution
2.Easy Identification of Program Code and Error-Handling Code
3.Propagation of Errors
4.Meaningful Error Reporting
5.Identifying Error Types
Java Exception Keywords
Java provides five keywords that are used to handle the exception.
Keyword Description

The "try" keyword is used to specify a block where we should place an exception
try code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

The "catch" block is used to handle the exception. It must be preceded by try block
catch which means we can't use catch block alone. It can be followed by finally block
later.

The "finally" block is used to execute the necessary code of the program. It is
finally
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

The "throws" keyword is used to declare exceptions. It specifies that there may
throws occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
Syntax
try-catch Block − try - catch block in java is used to handle exceptions. The try - block contains the code which
may throw an exception. The catch block catches the exception and handles the exception.

try
{
// Protected code
}
catch (ExceptionName e1)
{
// Catch block
}
Methods to print the Exception information:
1. printStackTrace()
This method prints exception information in the format of the Name of the exception: description of the
exception, stack trace.

//program to print the exception information using


printStackTrace() method

import java.io.*;

class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
2. toString()
The toString() method prints exception information in the format of the Name of the exception: description of
the exception.

//program to print the exception information using toString()


method

import java.io.*;

class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
}
}
3. getMessage()
The getMessage() method prints only the description of the exception.

//program to print the exception information using


getMessage() method

import java.io.*;

class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}
// Java Program to Demonstrate How Exception Is Thrown

class GFG {

public static void main(String args[])


{
// Taking an empty string
String str = null;
System.out.println(str.length());
}
}
class GFG {

public static void main(String[] args)


{
int[] arr = new int[4];

int i = arr[4];

// This statement will never execute


System.out.println("Hi, I want to execute");
}
}
Handling Multiple Exceptions
Handling Multiple exceptions is nothing but having multiple catch blocks for a single try block
and handling multiple exceptions occurring in code present in try block. We will handle catch
different kind of exceptions and handle them using each catch block.
Java Catch Multiple Exceptions
Java Multi-catch block
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.

Flowchart of Multi-catch Blo


Java Program to Use finally block for Catching Exceptions
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the
connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally
contains all the crucial statements regardless of the exception occurs or not.
There are 3 possible cases where finally block can be used:
Case 1: When an exception does not rise
In this case, the program runs fine without throwing any exception and finally block execute after the try block.
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println("inside try block");
System.out.println(34 / 2);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception");
}
// Always execute
finally {

System.out.println(
"finally : i execute always.");

}
}
}
Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block, and finally block executes after the
catch block.
import java.io.*;
class GFG {

public static void main(String[] args)


{
try {
System.out.println("inside try block");
System.out.println(34 / 0);
}

catch (ArithmeticException e) {

System.out.println(
"catch : exception handled.");
}
finally {
System.out.println("finally : i execute always.");
}
}
}
Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so finally block execute after the try block
and after the execution of finally block program terminate abnormally, But finally block execute fine.
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");

// Throw an Arithmetic exception


System.out.println(34 / 0);
}
catch (NullPointerException e) {

System.out.println(
"catch : exception not handled.");
}

finally {
System.out.println( "finally : i will execute always.");
}
System.out.println("i want to run");
}
Basis of throw throws
Differences

Java throws keyword is used in the method


Java throw keyword is used throw an exception
signature to declare an exception which
1. Definition explicitly in the code, inside the function or the block
might be thrown by the function while the
of code.
execution of the code.

Using throws keyword, we can declare both


Type of exception Using throw keyword, we can only
checked and unchecked exceptions.
2. Usage propagate unchecked exception i.e., the checked
However, the throws keyword can be used
exception cannot be propagated using throw only.
to propagate checked exceptions only.

The throw keyword is followed by an instance of The throws keyword is followed by class
3. Syntax
Exception to be thrown. names of Exceptions to be thrown.

4. Declaration throw is used within the method. throws is used with the method signature.

We can declare multiple exceptions using


Internal We are allowed to throw only one exception at a time throws keyword that can be thrown by the
5.
implementation i.e. we cannot throw multiple exceptions. method. For example, main() throws
IOException, SQLException.
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 methods has to handle the exception using a try-catch block.

Syntax of Java throws


type method_name(parameters) throws exception_list

exception_list is a comma separated list of all the


exceptions which a method might throw.
public class TestThrows {
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}

System.out.println("Rest of the code..");


}
}
Java throw and throws Example
TestThrowAndThrows.java

public class TestThrowAndThrows


{
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}

public static void main(String args[])


{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
public class TestThrow {
void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
//ArithmeticException e=new ArithmeticException("\nNumber is negative, cannot calculate square");
//throw e;
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
public class TestThrows {
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}

System.out.println("Rest of the code..");


}
}
Annotations in Java
Annotations are used to provide supplemental information
about a program.
Annotations start with ‘@’.
Annotations do not change the action of a compiled
program.
Annotations help to associate metadata (information) to the
program elements i.e. instance variables, constructors,
methods, classes, etc.
Annotations are not pure comments as they can change the
way a program is treated by the compiler. See below code
for example.
Annotations basically are used to provide additional
information, so could be an alternative to XML and Java
@Override
@Override annotation assures that the subclass method is overriding the parent
class method. If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is
better to mark @Override annotation that provides assurity that method is
overridden.

class Animal{
void eatSomething(){System.out.println("eating something");}
}
class Dog extends Animal{
@Override
void eatsomething(){System.out.println("eating foods");}
}
class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}
// Java Program to Demonstrate that Annotations
class Base {
public void display()
{
System.out.println("Base display()");
}
}
class Derived extends Base {
@Override public void display(int x)
{
System.out.println("Derived display(int )");
}
public static void main(String args[])
{
// Creating object of this class inside main()
Derived obj = new Derived();

// Calling display() method inside main()


obj.display();
}
}
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");

for(Object obj:list)
System.out.println(obj);
If you remove the
@SuppressWarnings("unchecked") annotation,
}} it will show warning at compile time
because we are using non-generic
collection.
@Deprecated
@Deprecated annotation marks that this method is deprecated so compiler prints
warning. It informs user that it may be removed in the future versions. So, it is better
not to use such methods.

class A{
void m(){System.out.println("hello m");}

@Deprecated
void n(){System.out.println("hello n");}
}

class TestAnnotation3{
public static void main(String args[]){

A a=new A();
a.n();
}}
Java Custom Annotations
Java Custom annotations or Java User-defined annotations are easy to create and
use. The @interface element is used to declare an annotation. For example:

@interface MyAnnotation{}
Here, MyAnnotation is the custom annotation name.

Types of Annotation
There are three types of annotations.
1.Marker Annotation
2.Single-Value Annotation
3.Multi-Value Annotation

1) Marker Annotation
An annotation that has no method, is
called marker annotation. For
example:

@interface MyAnnotation{}
The @Override and @Deprecated are
marker annotations.
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}

We can provide the default value also. For example:


@interface MyAnnotation{
int value() default 0;
}

3) Multi-Value Annotation
An annotation that has more than one
method, is called Multi-Value annotation.
For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
Built-in Annotations used in custom annotations in
java
•@Target
•@Retention
•@Inherited
•@Documented
@Target
@Target tag is used to specify at which type, the annotation
is used.
//Creating annotation
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation{
int value();
}
class Hello{
@MyAnnotation(value=10)
public void sayHello(){System.out.println("hello annotation");}
}
class TestCustomAnnotation1{
public static void main(String args[])throws Exception{

Hello h=new Hello();


Method m=h.getClass().getMethod("sayHello");

MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+manno.value());
}}
@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation
marks the annotation to be inherited to subclasses.

@Documented
The @Documented Marks the annotation for inclusion in the documentation.
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.


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.

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)
1) Process-based Multitasking (Multiprocessing)
 Each process has an address in memory. In other words, each process allocates a separate memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and loading registers, memory maps, updating
lists, etc.
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.

What is Thread in java


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. Ex-(playing music,file downloading,printing file,work on
msword)

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.

Note: At a time one thread is executed only.


Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes
within a process.
Threads can be created by using two mechanisms :
1.Extending the Thread class

2.Implementing the Runnable Interface

1.Thread creation by extending the Thread class


We create a class that extends the java.lang.Thread class. This class overrides the run() method available in
the Thread class. A thread begins its life inside run() method. We create an object of our new class and call
start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Java Thread Methods
S.N. Modifier and Type Method Description
1) void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.

4) static Thread currentThread() It returns a reference to the currently executing thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.


class MultithreadingDemo extends Thread {
public void run()
{
try {
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
public class Multithread1 {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object= new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a
Thread object and call start() method on this object.

class MultithreadingDemo implements Runnable {


public void run()
{
try {
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}}}
class Multithread {
public static void main(String[] args)
{
int n = 8;
for (int i = 0; i < n; i++) {
MultithreadingDemo t=new MultithreadingDemo();
Thread object= new Thread(t);
object.start();
}}}
Difference between Thread.start() and Thread.run() in Java
In Java’s multi-threading concept, start() and run() are the two most important methods.

New Thread creation: When a program calls the start() method, a new thread is created and then
the run() method is executed. But if we directly call the run() method then no new thread will be
created and run() method will be executed as a normal method call on the current calling thread itself and
no multi-threading will take place.
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "+ Thread.currentThread().getName());
System.out.println("run() method called");
}}

class Multithread3
{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
}
}
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());

System.out.println("run() method called");


}
}

class Multithread4{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.run();
}
}
 when we called the run() method of our MyThread class, no new thread is created and the run() method is
executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is
called as a normal function call.
 In Java’s multi-threading concept, another most important difference between start() and run() method is that
we can’t call the start() method twice otherwise it will throw an IllegalStateException whereas run() method
can be called multiple times as it is just a normal method calling
LifeCycle of a Thread in java.
A thread goes through various stages while executing or completing task like new/born, ready, runnable and finally dead
state, these states are nothing but is life cycle of a Thread.
Below is the diagram which tells the story of Thread life cycle i.e. how a thread goes into ready state from born state and
from ready to running and finally into Dead state. Please go through this to understand the life cycle of a Thread.

1.When we write MyThread t1=new MyThread() then thread is in the New/Born state.
2.When we call t.start() method then thread enters into Ready State or Runnable State.
3.If Thread Scheduler allocates the processor to Thread then Thread enters into Running State.
4.If run() method completes successfully then thread enters into Dead State.
5. If a running thread calls the Thread.yield() method then thread enters into ready state from
running state to give chance to other waiting thread of same priority immediately.
6. If thread calls the wait() method then running thread will enters into waiting state. if this thread got any
notification by method notify()/notifyAll() then it enters into another waiting state to get lock.so when the
thread comes out of waiting state to another waiting state to get lock is-

A) If waiting thread got notification.


B) If time expires.
C) If waiting thread got interrupted.
LifeCycle of a Thread in java.
Synchronization in Java
Multi-threaded programs may often come to a situation where multiple threads try to access the same
resources and finally produce erroneous and unforeseen results.
Why use Java Synchronization?
Java Synchronization is used to make sure by some synchronization method that only one thread can access the
resource at a given point in time.
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization?


The synchronization is mainly used to

• To prevent thread interference.


• To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

Process Synchronization
Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1.Mutual Exclusive
1. Synchronized method.
2. Synchronized block(more faster).
3. Static synchronization.
2.Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using
the following three ways:
1.By Using Synchronized Method
2.By Using Synchronized Block
3.By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it.
By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.
Multithreading problem in java
Multithreading Solution using Method level Synchronisation in java
Multithreading Solution using block level Synchronisation in java
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent.

class Table{ class MyThread2 extends Thread{


void printTable(int n){//method not synchronized Table t;
for(int i=1;i<=5;i++){ MyThread2(Table t){
System.out.println(n*i); this.t=t;
try{ }
Thread.sleep(400); public void run(){
}catch(Exception e){System.out.println(e);} t.printTable(100);
} }
} }
}
class MyThread1 extends Thread{ class TestSynchronization1{
Table t; public static void main(String args[]){
MyThread1(Table t){ Table obj = new Table();//only one object
this.t=t; MyThread1 t1=new MyThread1(obj);
} MyThread2 t2=new MyThread2(obj);
public void run(){ t1.start();
t.printTable(5); t2.start();
} }
}
}
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.
//example of java synchronized method class MyThread2 extends Thread{
class Table{ Table t;
synchronized void printTable(int n){ MyThread2(Table t){
for(int i=1;i<=5;i++){ this.t=t;
System.out.println(n*i); }
try{ public void run(){
Thread.sleep(400); t.printTable(100);
}catch(Exception e){System.out.println(e);} }
} }

} public class TestSynchronization2{


} public static void main(String args[]){
Table obj = new Table();//only one object
class MyThread1 extends Thread{ MyThread1 t1=new MyThread1(obj);
Table t; MyThread2 t2=new MyThread2(obj);
MyThread1(Table t){ t1.start();
this.t=t; t2.start();
} }
public void run(){ }
t.printTable(5);
}

}
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the method.
• Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such cases, we can
use synchronized block.
• If we put all the codes of the method in the synchronized block, it will work same as the synchronized method.

Points to Remember
• Synchronized block is used to lock an object for any shared
resource.
• Scope of synchronized block is smaller than the method.
• A Java synchronized block doesn't allow more than one JVM,
to provide access control to a shared resource.
• The system performance may degrade because of the
slower working of synchronized keyword.
• Java synchronized block is more efficient than Java
synchronized method.
class Table
{ class MyThread2 extends Thread{
void printTable(int n){ Table t;
synchronized(this){//synchronized block MyThread2(Table t){
for(int i=1;i<=5;i++){ this.t=t;
System.out.println(n*i); }
try{ public void run(){
Thread.sleep(400); t.printTable(100);
}catch(Exception e){System.out.println(e);} }
} }
}
}//end of the method public class TestSynchronizedBlock1{
} public static void main(String args[]){
Table obj = new Table();//only one object
class MyThread1 extends Thread{ MyThread1 t1=new MyThread1(obj);
Table t; MyThread2 t2=new MyThread2(obj);
MyThread1(Table t){ t1.start();
this.t=t; t2.start();
} }
public void run(){ }
t.printTable(5);
}

}
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on
object.

static synchronization Lock1 for object1

Lock2 for object2

Static synchronization ensures that only one thread can access a static
synchronized method or block at a time, even if multiple threads are running.
• When there are more objects of a class, It acquires only the lock of the particular instance. To maintain the
Synchronized behavior, we need a class-level lock rather than an instance-level lock which can be
achieved by Static Synchronization.
• Static Synchronized method is also a method of synchronizing a method in Java such that no two threads
can act simultaneously static upon the synchronized method. The only difference is by using Static
Synchronized. We are attaining a class-level lock such that only one thread will operate on the method.
The Thread will acquire a class-level lock of a Java class, such that only one thread can act on the static
synchronized method.
Real life Applications of Multithreading and Synchronisation in java
Scenario1: Ticket Booking System In this example, we have a shared resource, available tickets, and multiple
users (threads) attempting to book tickets concurrently. Synchronization ensures that no two threads book the same ticket
simultaneously.

Scenario2: ATM Machine Operations


Multiple users access an ATM machine to withdraw money from a shared bank account.
Explanation: Synchronization ensures that two users don't withdraw money simultaneously if the account balance isn't
sufficient.

Scenario3: File Writing in a Multi-Threaded Application


Multiple threads write data to the same log file. Synchronization ensures no two threads write simultaneously, avoiding
corrupt data.
Explanation: A synchronized block prevents concurrent access to the file resource.

Scenario4: Shared Printer in an Office


Multiple employees send print jobs to a shared printer. Synchronization ensures that the printer processes one job at a
time.
Explanation: The printer acts as a shared resource, and threads synchronize access to it.

Scenario5: Inventory Management System


Multiple users update the stock of a product in a shared inventory system.
Explanation: Synchronization ensures that no two users update the stock count simultaneously, preventing inconsistencies.
Why Synchronization in Real Life?
1.Thread Safety: Avoids race conditions in multi-threaded environments.
2.Resource Consistency: Ensures that shared resources like files, databases, or devices
are used consistently.
3.Reliability: Prevents data corruption and ensures system reliability in concurrent
scenarios.
These examples show how synchronization is crucial for thread-safe, consistent
operations in real-world applications.
Java Package
 A java package is a group of similar types of classes, interfaces and sub-
packages.

 Package in java can be categorized in two form, built-in package and user-
defined package.

 There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces
so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in
packages are:

java.lang: Contains language support classes(e.g classes which defines primitive data types, math operations). This
package is automatically imported.
java.io: Contains classes for supporting input / output operations.
java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date /
Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc). 6)
java.net: Contain classes for supporting networking operations.
User-defined packages: These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name of the package). Then create
the MyClass.java inside the directory with the first statement being the package names.and compile it
Then create new program PrintName.java in other directory and calls the package in the program

Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Why Use User-Defined Packages in These Applications?

:
1.Organized Structure

•Helps developers logically group classes related to a specific functionality.


2.Code Reusability:
•Classes in a package can be reused across different modules or applications.
3.Encapsulation:
•Provides control over the visibility of classes and members using public, private, and protected access modifiers.
4.Ease of Maintenance:
•Modular design makes debugging and updating specific features easier.
5.Prevents Name Conflicts:
•Classes with the same name in different packages won’t clash.
These examples show how user-defined packages enhance the development and organization of complex real-world a
Why Use User-Defined Packages in These Applications?
1.Organized Structure:
•Helps developers logically group classes related to a specific functionality.
2.Code Reusability:
•Classes in a package can be reused across different modules or applications.
3.Encapsulation:
•Provides control over the visibility of classes and members using public, private, and protected
access modifiers.
4.Ease of Maintenance:
•Modular design makes debugging and updating specific features easier.
5.Prevents Name Conflicts:
•Classes with the same name in different packages won’t clash.
Steps to Create and Use a User-Defined Package
Step 1: Create a PackageCreate a directory named mathoperations to match the package name.Add the following Java
classes to this directory.

Class: Addition.java
package mathoperations;

public class Addition {


public int add(int a, int b) {
return a + b;
} Class: Division.java
}
package mathoperations;
Class: Subtraction.java
public class Division {
package mathoperations;
public double divide(int a, int b) {
if (b == 0) {
public class Subtraction {
throw new ArithmeticException("Division by zero is not
public int subtract(int a, int b) {
allowed.");
return a - b;
}
}
return (double) a / b;
}
}
}
Step 2: Use the Package in a Main ClassCreate a class outside
the mathoperations package to use these classes.Class:
CalculatorApp.java
import mathoperations.Addition; or import mathoperations.*;
import mathoperations.Subtraction;
import mathoperations.Multiplication;
import mathoperations.Division;

public class CalculatorApp {


public static void main(String[] args) {
Addition add = new Addition();
Subtraction subtract = new Subtraction();
Multiplication multiply = new Multiplication();
Division divide = new Division();

int num1 = 10, num2 = 5;

System.out.println("Addition: " + add.add(num1, num2));


System.out.println("Subtraction: " + subtract.subtract(num1, num2));
System.out.println("Multiplication: " + multiply.multiply(num1, num2));
System.out.println("Division: " + divide.divide(num1, num2));
}
} Compiling and Running the Program
Step 1: Compile the Package Classes Navigate to the directory containing mathoperations and compile the classes:
Hospital Management System
Contains three classes:
• PatientManager: Handles patient details.
• AppointmentManager: Manages appointments.
• BillingManager: Processes billing.

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