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

Unit-4 Java

Uploaded by

manitechgamer
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)
68 views

Unit-4 Java

Uploaded by

manitechgamer
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/ 42

4.

Exception Handling &MultiThreaded


Programming
4.1 DESCRIBE SOURCES OF ERRORS :

Errors in Java :
• Errors in Java occur when a programmer violates the rules of Java programming language.

• It might be due to programmer's typing mistakes while developing a program.

It may produce incorrect output or may terminate the execution of the program abnormally.

• For example, if you use the right parenthesis in a Java program where a right brace is needed,
you have made a syntax error. You have violated the rules of Java language.

• Therefore, it is important to detect and fix properly all errors occurring in a program so that
the program will not terminate during execution.

Types of Errors in Java Programming :


When we write a program for the first time, it usually contains errors. These errors are mainly
divided into three types:

1. Compile-time errors (Syntax errors)

2. Runtime errors

3. Logical errors

Java Compile Time Errors :


• Compile-time errors occur when syntactical problems occur in a java program due to incorrect
use of Java syntax.

• These syntactical problems may be missing semicolons, missing brackets, misspelled keywords,
use of undeclared variables, class not found, missing double-quote in Strings, and so on. These
problems occurring in a program are called syntax errors in Java.

•Since all syntax errors are detected by Java compiler, therefore, these errors are also known as
compile time errors in Java.

•When Java compiler finds syntax errors in a program, it prevents the code from compile
successfully and will not create a class file until errors are not corrected. An error message will be
displayed on the console screen.

•These errors must be removed by debugging before successfully compile and run the program.

Program source code 1:


public class CompileTimeErrorEx{
public static void main (String[] args) {
System. outprintln ("a") // Syntax error. Semicolon missing.
}}

Compile time error in Java code:


When you will try to compile the above program, Java compiler will tell you where errors are in
the program. Then you can go to the appropriate line, correct error, and recompile the
program.Let's create a program where we will try to call the undeclared variable. In this case, we
will get unresolved compilation problem.

Program source code 2:


public class MisspelledVar{
public static void main (String[] args){
int x = 20, y = 30;// Declare variable sum.
int sum = x + y;// Call variable Sum with Capital S. Calling of undeclared variable.
System. outprintin ("Sum of two numbers: " + Sum) ;
}}
Output:
Main.java:9: error: cannot find symbol
System.out.println ("Sum of two numbers: " + Sum) ;
^
symbol: variable Sum
location: class MisspelledVar

Runtime Errors in Java.


• Runtime errors occur when a program is successfully compiled creating the class file but does
not run properly. It is detected at run time (i.e. during the execution of the program).

• JVM is responsible to detect runtime errors while the program is running.

• Such a program that contains runtime errors may produce wrong results due to wrong logic or
terminate the program. These runtime errors are usually known as exceptions.

For example, if a user inputs a value of string type in a program but the computer is expecting an
integer value, a runtime error will be generated.

The most common runtime errors are as follows:


1. Dividing an integer by zero.

2. Accessing an element that is out of range of the array.

3. Trying to store a value into an array that is not compatible type.

4. Passing an argument that is not in a valid range or valid value for a method.

5. Striving to use a negative size for an array.

6. Attempting to convert an invalid string into a number and many more.


When such errors are encountered in a program, Java generates message and terminates the
program abnormally.

To handle these kinds of errors during the runtime, we use exception handling technique in java
program.

Let's take different kinds of example programs to understand better. In this program, we will
divide an integer number by zero. Java compiler cannot detect it.

Program source code 3:


public class DivisionByZeroError {
public static void main (String[] args) {
inta = 20, b = 5, c = 5;
int z = a/ (b-c); // Division by zero.
System. outprintln ("Result: " +z) ;
}
}
Output:
Exception in thread "main" java.lang. ArithmeticException: / by zero at errors Program.
DivisionByZeroError. main (DivisionByZeroError.java:8)

The above program is syntactically correct. There is no syntax error and therefore, does not cause
any problem during compilation. While executing, runtime error occurred that is not detected by
compiler.

The error is detected by JVM only in runtime. Default exception handler displays an error
message and terminates the program abnormally without executing further statements in the
program.

Let's take an example program where we will try to retrieve a value from an array using an index
that is out of range of the array.

Program source code 4:


public class AccessingValueOutOfRangeError {
public static void main (String[ ] args) {
intarr[] = {1, 2, 3, 4, 5}; // Here, array size is 5.
System. out. println ("Value at 5th position: "+arr [5]) ;
}
}
Output:
Exception in thread "main" java. lang. ArrayIndexOutOfBoundsEception: 5

Aterrors Program. AccessingValueOutOfRangeError.main

Accessing ValueOutOfRangeError.java:9)

Logical Errors in Java Program:


• Logical errors in Java are the most critical errors in a program and they are difficult to detect.
These errors occur when the programmer uses incorrect logic or wrong formula in the coding.
• The program will be compiled and executed successfully but does not return the expected
output.

• Logical errors are not detected either by Java compiler or JVM (Java runtime system). The
programmer is entirely responsible for them. They can be detected by application testers when
they compare the actual result with its expected result.

For example, a programmer wants to print even numbers from an array but he uses division (/)
operator instead of modulus (%) operator to get the remainder of each number. Due to which
he got the wrong results.

Program source code 5:


public class LogicalErrorEx {
public static void main (String[] args) {
int a[]= {1, 2, 5, 6, 3, 10, 12, 13, 14} ;
System. out. println ("Even Numbers:") ;
for (inti = 0; i<a. length; i++){
if (a [i] / 2 == 0){ // Using wrong operator.
System. out .println (a[i]) ;
}}}}
Output:
Even Numbers: 1

As you can see the program is successfully compiled and executed but the programmer got the
wrong output due to logical errors in the program.

A software engineer in a company also commits several errors while designing the project or
developing code.

These errors in a program are also called bugs and the process of fixing these bugs is called
debugging.

4.2 GIVE ADVANTAGES OF EXCEPTION HANDLING :


1. Ensures the Continuity of the Program

One of the key benefits of exception handling is that it ensures the continuity of the program.
Without proper exception handling, an unhandled exception would cause the program to
terminate abruptly, which can lead to data loss & other issues.

2. Enhances the Robustness of the Program

Exception handling allows for the program to anticipate and recover from errors, thus making
the program more robust and resistant to unexpected conditions.

3. Improves the Readability & Maintainability of the Code

Proper exception handling also improves the readability & maintainability of the code. By
catching and handling exceptions, the program can provide clear error messages that accurately
describe the error and provide information on how to resolve the issue.
4. Allows for more Accurate Error Reporting

Exception handling allows the program to catch & report errors in a more accurate & detailed
manner.

5. Facilitates Debugging and Troubleshooting

Exception handling allows developers to quickly identify and resolve issues, reducing the amount
of time and resources required for debugging.

6. Improves the Security of the Program

Exception handling can also improve the security of a program by preventing sensitive
information from being exposed in the event of an error. By catching and handling exceptions,
the program can prevent sensitive information, such as passwords.

7. Provides a Better user Experience

Proper exception handling allows the program to anticipate and recover from errors, providing a
more stable user experience.

8. Enables the use of error-recovery Mechanisms

Exception handling enables the use of error-recovery mechanisms, such as retries or fallbacks,
which can improve the reliability and availability of the program.

9. Improves the Scalability and Performance of the Program

Proper exception handling can also improve the scalability and performance of a program by
reducing the amount of unnecessary processing and resources consumption. By catching and
handling exceptions, the program can avoid performing unnecessary operations and releasing
resources that are no longer needed, reducing the overall load on the system and improving
performance.

4.3 EXPLAIN TYPES OF EXCEPTIONS CHECKED AND UNCHECKED :


Types of Java Exceptions: There are mainly two types of exceptions: checked and
unchecked.

Difference between Checked and Unchecked Exceptions:


1) Checked Exception: The classes that directly inherit the Throwable class except Runtime
Exception and Error are known as checked exceptions.

For example, 10Exception, SQLException, etc.

Checked exceptions are checked at compile-time.

2) Unchecked Exception:The classes that inherit the Runtime Exception are known as
unchecked exceptions.
For example, ArithmeticException, ArrayIndexOutOfBoundsException, at run time.

NullPointerException, etc.

Unchecked exceptions are not checked at compile-time, but they are checked at run time.

4.4WRITE SAMPLE PROGRAMS TO MAKE USE OF TRY, CATCH, FINALLY,


THROW, THROWS :

Java try-catch block:

Java try block:


• Java try block is used to enclose the code that might throw an exception. It must be used
within the method.

• If an exception occurs at the particular statement in the try block, the rest of the block code
will not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.

• Java try block must be followed by either catch or finally block.

• Syntax of Java try-catch.

try{
//code that may throw an exception
} catch (Exception_class _Name ref) { }
• Syntax of try-finally block
try{
//code that may throw an exception
}finally { }
Java catch block.
• Java catch block is used to handle the exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception (i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.

• The catch block must be used after the try block only. You can use multiple catch block with a
single try block.

• Internal Working of Java try-catch block.

• The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:

a. Prints out exception description.

b. Prints the stack trace (Hierarchy of methods where the exception occurred).
c. Causes the program to terminate.

• But if the application programmer handles the exception ,the normal flow of the application is
maintained, i.e., rest of the code is executed.

• Problem without exception handling : Let's try to understand the problem if we don't use a
try-catch block.

Example 1: Try Catch Examplel.java

public class TryCatchExamplel {


public static void main (Stringll args) {
int data=50/0; //may throw exception
System. out.println ("rest of the code") ;
}
}
Output:
Exception in thread "main" java lang. ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed fin such case, the rest of
the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is handled, all the code
below the exception won't be executed.

Solution by exception handling:Let's see the solution of the above problem by a java try-catch
block.

Example 2: Try Catch Example 2.java:

public class TryCatchExample2 {


public static void main (String[] args) { try
int data=50/0; //may throw exception
}
catch (ArithmeticException e) //handling the exception
System. out. printin (e) ;
}
System. out. println ("rest of the code") ;
Output:
java.lang.ArithmeticException: / by zerorest of the code

As displayed in the above example, the rest of the code is executed, i.e., the rest of the code
statement is printed.

Example 3:Let's see an example to handle another unchecked exception.

TryCatchExample3.java

public class TryCatchExample {


public static void main (String[] args) {
try {
intarr []={ 11,3, 5, 7};
System. out. println (arr [10]); //may throw exception
// handling the array exception
}catch (ArrayIndexOutOfBoundsException e){
System. out. println (e) ;
System. out. println ("rest of the code") ; }
}}
Output:
java.lang.ArrayIndexOutOfBoundsException: 10

rest of the code.

Java finally block.

• Java finally block is a block used to execute important code such as closing the connection, etc.

• Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occur or
not.

• The finally block follows the try-catch block.

Note: If you don't handle the exception, before terminating the program, JM executes finally
block (if any).
The purpose of finally block:
•Finally block in Java can be used to put "cleanup" code such as closing a file, closing connection,
etc.

• The important statements to be printed can be placed in the finally block.

Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur


Let's see the below example where the Java program does not throw any exception, and the
finally block is executed after the try block.

Test Finally Block.java.

classTestFinallyBlock {
public static void main (String args []) {
try{
//below code do not throw any exception
int data=25/5;
System. out. println (data) ; }
//catch won't be executed
catch (NullPointerException e) {
System. out. println (e) ;

finally {
//executed regardless of exception occurred or not
System. out. println ("finally block is always executed") ;
System. out .println ("rest of the code...");
}}}
Output:
5

finally block is always executed

rest of the code ...

Case 2:When an exception occur but not handled by the catch block
Let's see the following example. Here, the code throws an exception however the catch block
cannot handle it. Despite this, the finally block is executed after the try block and then the
program terminates abnormally.

TestFinallyBlockl.java.

public class TestFinallyBlock1 {


public static void main (String args[]) {
try {
System.out.println ("Inside the try block") ; //below code throws divide by zero exception
int data=25/0;
System. out.println (data) ;
} //cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch (NullPointerException e) {
System. out. println (e) ;
}
//executes regardless of exception occured or not
finally {
System. out. println ("finally block is always executed") ;
System. out. println("rest of the code...") ;
}} }
Output:
Inside the try block
finally block is always executed
Exception in thread "main" java.lang. ArithmeticException: / by zero
at TestFinallyBlock1.main(TestFinallyBlock1.java:9)
Case 3: When an exception occurs and is handled by the catch block
Example: Let's see the following example where the Java code throws an exception and the
catch block handles the exception. Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.

TestFinallyBlock2.java.
public class TestFinallyBlock2{
public static void main (String args[]) { try {
System. out .println ("Inside try block") ;
//below code throws divide by zero exception
int data=25/0;
System. out. println (data) ;
}
//handles the Arithmetic Exception / Divide by zero exception
catch (ArithmeticException e) {
System. out.println ("Exception handled") ;
System. out. println (e) ;
}
//executes regardless of exception occured or not
finally{
System. out.println ("finally block is always executed") ;
System. out.println("rest of the code...") ;
}}}
Output:
Inside try block
Exception handled
Java lang. ArithmeticException: / by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only
one finally block.
Note: The finally block will not be executed if the program exists(either by calling System.exit()
or by causing a fatal error that causes the process to abort).

Java throw Exception.

• The Java throw keyword is used to throw an exception explicitly.

• We specify the exception object which is to be thrown. The Exception has some message with
it that provides the error description. These exceptions may be related to user inputs, server, etc.

• We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.

• We can also define our own set of conditions and throw an exception explicitly using throw
keyword.

For example, we can throw ArithmeticException if we divide a number by another number.


Here, we just need to set the condition and throw exception using throw keyword.

• The syntax of the Java throw keyword is given below.

Throw new exception _class ("error message");

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

Where the Instance must be of type Throwable or subclass of Throu example, Exception is the
sub class of Throwable and the user-defined ex usually extend the Exception class.

Java throw keyword Example.


Example 1: Throwing Unchecked Exception

In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the Arithmetic Exception otherwise print a
message welcome to vote.

Test Throw 1.java.


public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate (int age) {
if (age<18) {
//throw Arithmetic exception if not eligible to vote
throw new Arithmetic Exception ("Person is not eligible to vote"); }
else {
System. outprintin ("Person is eligible to vote!!");
}}
//main method
public static void main (String args []) {
//calling the function validate (13) ;
System. out-printin ("rest of the code...");
}}
Output:
Exception in thread "main" java.lang. Arithmetic Exception: Person is not eligible to vote

at Test Throw 1.validate (Test Throw1.java:8) at Test Throw 1. main (Test Throwl.java:18)

The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.

Java throws keyword.


• The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide
the exception handling code so that the normal flow of the program can be maintained

• Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not checking
the code before it being used.

• Syntax of Java throws

return type method_ name () throws exception_class_name{

//method code }

Only checked exception should be declared, because unchecked exception is under our control so
we can correct our code.

Advantage of Java throws keyword.

• Checked Exception can be propagated (forwarded in call stack).

• It provides information to the caller of the method about the exception.

Java throws Example: Let's see the example of Java throws clause which describes that checked
exceptions can be propagated by throws keyword.

Testthrows1.java.

import java. io. IOException;


class Testthrows1{
void m() throws IOException{
throw new IOException ("device error"); //checked exception
}
void n() throws IOException{
m () ;
}
void p() {
try { n() ;
}catch (Exception e) (System. out printin ("exception handled") ; }
}
public static void main (String args []) {
Testthrows1 obj-new Testthrows1 () ;
obj.p() ;
System. out. println ("normal flow...");
}}
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or declare the
exception.
There are two cases:
Case 1:We have caught the exception i.e. we have handled the exception using try/catch block.

Case 2:We have declared the exception i.e. specified throws keyword with the method.

Case 1: Handle Exception Using try-catch block


In case we handle the exception, the code will be executed fine whether exception occurs during
the program or not.

Testthrows2.java

import java.io.*;
class M{
void method () throws IOException{
throw new IOException ("device error") ;
} }
public class Testthrows2{
public static void main (String args []) { try {
M m=new M() ;
m. method () ;
catch (Exception e) {
System. out. println ("exception handled") ; }
System. out. println ("normal flow...");
}}
Output:
exception handled
normal flow...
Case 2: Declare Exception.
In case we declare the exception, if exception does not occur, the code willbe executed fine.

In case we declare the exception and the exception occurs, it will be thrown al runtime because
throws does not handle the exception.

Let's see examples for both the scenario.

A. If exception does not occur


Testthrows3. java

import java.io.*;
class M{
void method () throws IOException {
System.out.println ("device operation performed") ;
}}
class Testthrows3 {
public static void main (String args []) throws IOException { // declare exception
M m-new M() ;
m. method () ;
System.out.println ("normal flow...");
}}
Output:
device operation performed
normal flow...
B) If exception occurs
Testthrows4. java

import java.io.*;
class M{
void method () throws IOException{
throw new IOException ("device error") ; } }
class Testthrows4{
public static void main (String args[]) throws IOException{// declare exception
M m=new M() ;
m.method () :
System.out.println ("normal flow...");
}}
Output:
Exception in thread "main" java.io. IOException: device error at M. method
(TestThrows4.java:4)

at TestThrows4.main(TestThrows4.java:10)

Brief explanation of the above keywords:


Java Exception Keywords:Java provides five keywords that are used to handle the exception.
The following table describes each.

Keyword Description
Try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
Catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone.
It can be followed by finally block later.
Finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
Throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.

4.5 EXPLAIN CONCEPT OF MULTI-CATCH STATEMENTS WITH EXAMPLE


Java Multi-catch block

• A try block can be followed by one or more a catch blocks. Each catch block must contain a
different exception handler. So if you have to perform different tasks at the occurrence of
different exceptions, use java multi catch block.

• At a time only one exception occurs and at a time only one catch blocks

• All catch blocks must be ordered from most specific to most general, i.e. catch for Arithmetic
Exception must come before catch for Exception.

Flowchart of Multi-catch Block

Example 1: Let's see a simple example of java multi-catch block.


MultipleCatchBlock1.java

public class MultipleCatchBlock1 {


public static void main (String[] args) {
try{
int a[]=new int [5]; a [5] =30/0;}
catch (ArithmeticException e){
System.out.println ("Arithmetic Exception occurs") ;
}
catch (ArrayIndexOutOfBoundsException e){
System. out. println ("Array Index Out Of Bounds Exception occurs") ;
}
catch (Exception e){
System. out. println ("Parent Exception occurs") ;
}
System. out. println ("rest of the code") ;
}}
Output:
Arithmetic Exception occurs
rest of the code
Example 2: MultipleCatchBlock2.java
public class MultipleCatchBlock2 {
public static void main (String[] args) {
try{
int a[]new int [5];
System. out .printin (a [10]) ;
}
catch (ArithmeticException e){
System. out. println ("Arithmetic Exception occurs") ; }
catch (ArrayIndexOutOfBoundsException e){
System. outprintln ("Array Index Out Of Bounds Exception occurs") ;
}
catch (Exception e){
System. outprintin ("Parent Exception occurs") ;}
System. outprintin ("rest of the code") ;
}}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code

4.6 EXPLAIN HOW TO WRITE NESTED TRY IN EXCEPTION HANDLING

Java Nested try block


• In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.
• For example, while the outer try block can handle the Arithemetic Exception (division
by zero), the inner try block can be used to handle Array Index Out Of
BoundsException.

• Why use nested try block.

Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.

Syntax:

//main try block


try {
statement 1;
statement 2;
} //try catch block within another try block
try{
statement 3;
statement 4;
//try catch block within nested try block
try{
statement 5;
statement 6;
}
catch (Exception e2){
//exception message
}
}
catch (Exception e1) {
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3) {
//exception message
}
Java Nested try Example1: Let's see an example where we place a try block within
another try block for two different exceptions.
NestedTryBlock.java

public class NestedTryBlock{


public static void main (String args []) { //outer try block try1
try{
//inner try block 1
System. out.println ("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch (ArithmeticException e){
System. outprintln (e) ;
}
//inner try block 2
try{
int a[]=new int [5];
//assigning the value out of array bounds
a [5] =4;}
//catch block of inner try block 2
catch (ArrayIndexOutOfBoundsException e){
System. out. println (e) ;}
System. outprintln ("other statement") ;
//catch block of outer try block
catch (Exception e) {
System. outprintln ("handled the exception (outer catch) ") ; }
system. outprintln ("normal flow..");}}
Output:
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
handled the exception (outer catch)
normal flow..

NestedTryBlock.java

public class NestedTryBlock2 {


public static void main (String args[]){
// outer (main) try block
try
{//inner try block 1
try {// inner try block 2
try {
intarr[] = {1, 2, 3, 4 };
//printing the array element out of its bounds
System. out. println (arr [10]) ;}
// to handles ArithmeticException
catch (ArithmeticException e) {
System. outprintin ("Arithmetic exception");
System. out-println(" inner try block 2");}}
// to handle ArithmeticException
catch (ArithmeticException e) {
System. out. println ("Arithmetic exception") ;
System. out. println ("inner try block 1") ;}}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out. print (e4) ;
System. outprintln(" outer (main) try block") ;}
catch (Exception e5)
{System. out print ("Exception") ;
System.outprintln(" handled in main try-block");}}}
Output:
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 4
outer (main) try block
4.7 DESCRIBE BUILT IN EXCEPTIONS:
Types of Exception in Java

• In Java, exception is an event that occurs during the execution of a program and
disrupts the normal flow of the program's instructions.

• Bugs or errors that we don't want and restrict our program's normal execution of code
are referred to as exceptions.

• Exceptions can be categorized into two ways:

• Built-in Exceptions

• User-Defined Exceptions
Built-in Exception:

• Exceptions that are already available in Jautoderries are referred to as ception


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 sustem has
shown a compilation error.

CheckedExceptionExample.java.

import java.io.*;
classCheckedExceptionExample {
public static void main (String args []) {
FileInputStreamfile_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 () ;}}
Output:
error
usersajeet \OneDrive|Desktop\programs>-
Resolving the error:- We will use the try-catch block in the following way:
Exception. java.

import java.io.*;
class Exception{
public static void main (String args []) {
FileInputStream file_ data = null;
try {
file_data = new FileInputStream ("C: /Users/ajeet/OneDrive/Desktop/
programs/Hell. txt") ; }
catch (FileNotFoundExceptionfnfe){
System. out. println ("File Not Found!") ;}
int m;
try{
while ((m = file_data.read () ) != -1) {
System. out print ( (char)m) ;}
file data. close () ;}
catch (IOExceptionioe) {
System. outprintin("I/0 error occurred: "+ioe) ;}}
Output:
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.

Note: The RuntimeException class is able to resolve all the ur exceptions because of the
child-parent relationship.

UncheckedExceptionExamplel.java

classUncheckedExceptionExamplel {
public static void main (String args []){
int positive = 35;
int zero = 0;
int result = positive/zero;
//Give Unchecked Exception here.
System. outprintln (result) ;
}}
In the above program, we have divided 35 by 0. The code would be compiled
successfully, but it will throw an ArithmeticException error at runtime dividing a number
by 0 throws the divide by zero exception that is a l' exception.
Output:
ERROR!
Error: Division by zero!

UncheckedExceptionExample2.java
class UncheckedexceptionExample2 {
public static void main (String args[]){
intnum (] =(10,20, 30, 40,50, 60);
system. out-printin (num[7]) ;}}
Output:
In the above code, we are trying to get the element located at position 7, but the length
of the array is 6. The code compiles successfully, but throws the
ArrayIndexOutOfBoundsException at runtime.
4.8 DESCRIBE MULTITHREADING:
• Multithreading in Java is a process of executing multiple threads simultaneously.

• A thread is a lightweight sub-process, the smallest unit of processing.

Multiprocessing and multithreading, both are used to achieve multitasking.

• However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

• Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

• It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

• We can perform many operations together, so it saves time.

• 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 task simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:

Process-based Multitasking (Multiprocessing).

4.9 EXPLAIN THREAD LIFE CYCLE AND STATES :

Thread Life Cycle in Java with Examples

The thread can exist in different states. Just because a thread's start () method has been
called, it doesn't mean that the thread has access to the CPU and can start executing
straight away. Several factors determine how it will process.

Thread Life Cycle in Java

The life cycle of the thread in java is controlled by JVM. A thread goes through various
stages in its life cycle.

The java thread states are as follows:

.Newborn

.Runnable
.Running

.Blocked

.Dead

Following are the stages of the life cycle -

New - A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.

In simple words, a thread has been created, but it has not yet been started. A thread is
started by calling its start() method.

Runnable - The thread is in the runnable state after the invocation of the start| method,
but the thread scheduler has not selected it to be the running thread. A thread starts life
in the Ready-to-run state by calling the start method and waiting for its turn. The thread
scheduler decides which thread runs and for how long.

Running - When the thread starts executing, then the state is changed to a

"running" state. The scheduler selects one thread from the thread pool, and it starts
executing in the application.

Dead - This is the state when the thread is terminated. The thread is in a running state
and as soon as it is completed processing it is in a "dead state" Once a thread is in this
state, the thread cannot even run again.

Blocked (Non-runnable state):

This is the state when the thread is still alive but is currently not eligible to run.

A thread that is blocked waiting for a monitor lock is in this state.


A running thread can transit to one of the non-runnable states dependition the situation.
A thread remains in a non-runnable state until a special transtion

occurs. A thread doesn't go directly to the running state from a non-runnable state but
transits first to the Ready-to-run state.

Example for Thread Life Cycle in Java:-

Here we are giving a simple example of the Thread life cycle. In this t we will create a
Java class where we will create a Thread, and then we some of its methods that
represents its life cycle.

class A extends Thread {


public void run() {
System.out.println("Thread A");
System.out.println("Inside Thread A");
for (inti = 1; i<= 5; i++) {
System.out.println("i = " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace(); }}
System.out.println("Thread A Completed.");}}
class B extends Thread {
public void run() {
System.out.println("Thread B");
System.out.println("Inside Thread B");
for (inti = 1; i<= 5; i++) {
System.out.println("i = " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();} }
System.out.println("Thread B Completed.");}}
classThreadLifeCycleDemo {
public static void main(String[] args) {
A threadA = new A();
B threadB = new B();
threadA.start();
threadB.start();
try{
threadA.join();
} catch (InterruptedException e) {
e.printStackTrace(); }
System.out.println("Main Thread End"); }}
output:
Thread A
Inside Thread A
i=1
Thread B
Inside Thread B
i=1
i=2
i=2
i=3
i=3
i=4
i=4
i=5
i=5
Thread A Completed.
Thread B Completed.
Main Thread End.
Implementation of Thread States:

In Java, one can get the current state of a thread using the Thread.getState() method. The
java .lang. Thread. State class of Java provides the constants ENUM to represent the state
of a thread. These constants are:

public static final Thread.State NEW : It represents the first state of a thread that is the
NEW state.

public static final Thread.State RUNNABLE : It represents the runnable state.It means a
thread is waiting in the queue to run.

public static final Thread.State BLOCKED : It represents the blocked state. In this state,
the thread is waiting to acquire a lock.

public static final Thread. State WAITING : It represents the waiting state. A thread will
go to this state when it invokes the Object.wait() method, or Thread.join() method with
no timeout. A thread in the waiting state is waiting for another thread to complete its
task.

public static final Thread.State TIMED _WAITING : It represents the timed waiting state.
The main difference between waiting and timed waiting is the time constraint. Waiting
has no time constraint, whereas timed waiting has the time constraint.

public static final Thread.State TERMINATED : It represents the final state of a thread
that is terminated or dead. A terminated thread means it has completed its execution.
Java Program for Demonstrating Thread States: The following Java program shows some
of the states of a thread defined above.

FileName: ThreadState.java:

// ABC class implements the interface Runnable


class ABC implements Runnable {
public void run() {
try { // Moving thread t2 to the state timed waiting
Thread.sleep(100);
} catch (InterruptedExceptionie) {
ie.printStackTrace();}
System.out.println("The state of...");}}
// ThreadState class implements the interface Runnable
public class ThreadState implements Runnable {
public static Thread t1;
public static ThreadStateobj;
public static void main(String argvs[]) {
// Creating an object of the class ThreadState
obj = new ThreadState();
t1 = new Thread(obj);
// Thread t1 is spawned
System.out.println("The state of thread t1 after spawning it: " + t1.getState());
// Invoking the start() method on thread t1
t1.start();
// Thread t1 is moved to the Runnable state
System.out.println("The state of thread t1 after invoking the method start(): " +
t1.getState()
// Creating an object of the class ABC
ABC myObj = new ABC();
Thread t2 = new Thread(myObj);
// Thread t2 is created and is currently in the NEW state
System.out.println("The state of thread t2 after spawning it: " + t2.getState());

// Starting thread t2
t2.start();
// Thread t2 is moved to the runnable state
System.out.println("The state of thread t2 after calling the method start() on it: " +
t2.getState());
try { // Moving the thread t1 to the state timed waiting
Thread.sleep(200);
} catch (InterruptedExceptionie) {
ie.printStackTrace(); }
// The state of thread t2 after invoking the method sleep() on it
System.out.println("The state of thread t2 after invoking the method sleep() on it: " +
t2.getState());
try {
// Waiting for thread t2 to complete its execution
t2.join();
} catch (InterruptedExceptionie) {
ie.printStackTrace();}
// The state of thread t2 when it has completed its execution
System.out.println("The state of thread t2 when it has completed its execution: " +
t2.getState());}}
Output:
The state of thread t1 after spawning it: NEW
The state of thread t1 after invoking the method start(): RUNNABLE
The state of thread t2 after spawning it: NEW
The state of thread t2 after calling the method start() on it: RUNNABLE
The state of thread t2 after invoking the method sleep() on it: TIMED_WAITING
The state of thread t2 when it has completed its execution: TERMINATED
4.10 EXPLAIN HOW TO CREATING SINGLE THREAD WITH EXAMPLE
PROGRAM :

Java Threads: - There are two ways to create a thread:

 By extending Thread class


 By implementing Runnable interface.

1)Thread class:

Thread class provide constructors and methods to create imp perform operations Thread
dead. 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)

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 method on the thread.

public void sleep(long miliseconds): Causes the currently executing thre 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.

publicintgetPriority(): returns the priority of the thread.

publicintsetPriority(int priority): changes the priority of the thread.

public String getName): returns the name of the thread.

public void setName(String name): changes the name of the thread.

public Thread currentThread(): returns the reference of currently exe

publicintgetld(): returns the id of the thread.

publicThread.StategetState(): returns the state of the thread.

publicbooleanisAlive(): tests if the thread is alive.

public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.

public void suspend() : is used to suspend the thread (depricated).

public void resume(): is used to resume the suspended thread (depricated) .

public void stop(): is usea to stop the thread (depricated).

publicbooleanisDaemon(): tests if the thread is a daemon thread.

public void setDaemon (boolean b): marks the thread as daemon or userthread.

public void interrupt(): interrupts the thread.

publicbooleanisinterrupted(): tests if the thread has been interrupted.

public static boolean interrupted (): tests if the current thread has been interrupted.

2)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 newlycreated 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.

1. Java Thread Example by extending Thread class:

classMyThread extends Thread {


public void run() {
for (inti = 1; i< 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + " count: " + i); }}}
classSingleThreadExample {
public static void main(String[] args) {
MyThreadmyThread = new MyThread();
myThread.start();
for (inti = 1; i<= 5; i++) {
System.out.println("Main Thread count: " + i);}}}
output:
Main Thread count: 1
Main Thread count: 2
Main Thread count: 3
Main Thread count: 4
Main Thread count: 5
Thread 10 count: 1
Thread 10 count: 2
Thread 10 count: 3
Thread 10 count: 4
2. Java Thread Example by implementing Runnable interface
classMyThread implements Runnable {
public void run() {
for (inti = 1; i< 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + " count: " + i); }}
}classSingleThreadExample {
public static void main(String[] args) {
MyThreadmyRunnable=new MyThread();
Thread myThread=new Thread(myRunnable);
myThread.start();}}
output:
Thread 10 count: 1
Thread 10 count: 2
Thread 10 count: 3
Thread 10 count: 4
3. Using the Thread Class: Thread(String Name)
// FileName: MyThread1.java
public class MyThread1 {
public static void main(String args[]) {
// Creating an object of the Thread class using the constructor Thread(String name)
Thread t = new Thread("My first thread");
// The start() method moves the thread to the active state
t.start(); // Getting the thread name by invoking the getName() method
String str = t.getName();// Printing the thread name
System.out.println(str);}}
Output
My first thread
4. Using the Thread Class: Thread(Runnable r, String name)
// FileName: MyThread2.java
public class MyThread2 implements Runnable {
public void run() {
System.out.println("Now the thread is running ...");
} // Main method
public static void main(String[] args) {
// Creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// Creating an object of the class Thread using Thread(Runnable, String name)
Thread th1 = new Thread(r1, "My new thread")
// The start() method moves the thread to the active state
th1.start();}}
Output
Now the thread is running ...
4.11 EXPLAIN HOW TO CREATING MULTI THREAD WITH EXAMPLE PROGRAM:

Creating Multiple Threads in Java

Basically, when we need to perform several tasks at a time, we can create multiple
threads to perform multiple tasks in a program.

For example, to perform two tasks, we can create two threads and attach them to two
tasks. Hence, creating multiple threads in Java programming helps to perform more than
one task simultaneously.

Creating more than one thread to perform multiple taskscalled multithreading in Java. In
multiple threading programming, multiple threads are executing simultaneously that
improves the performance of CP because CPU is not idle if other threads are waiting to
get someresource

Multiple threads share the same address space in the heap memor Therefore, It is good to
create multiple threads to execute multiple tasrather than creating multiple processes.
Look at the below picture.
Benefits of Creating multiple threads in Java for Multitasking:

 Suppose when we go to watch a movie in a theater, generally, a person sdoor to


check and cutting the tickets.
 When we enter the hall, there is oneperson that stays to show seats to us. Suppose
there is one person (1 thread) to perform these two tasks.
 In this case, he has to first cut ticket and then come along with us to show seats.
 Then, he will go back to door to cut second ticket and then again enter the hall to
show seat for second ticket.
 Like this, he is taking a lot of time to perform these tasks one by one.
 If theatermanager employs two persons (2 threads) to perform these two tasks,
one personwill cut the ticket and another person will show seat.
 Thus, when the secondperson will be showing seat, the first person will cut the
ticket.
 Like this, bothpersons will act simultaneously and wastage of time will not
happen.

Let's create a Java program in which we will try to implement this realtime scenario.

Program code:

public class MyThread extends Thread {


// Declare a String variable to represent task.
String task;
// Constructor to initialize task.
MyThread(String task) {
this.task = task; }
public void run() {
for (inti = 1; i<= 5; i++) {
System.out.println(task + ":" + i);
try {
Thread.sleep(1000); // Pause the thread execution for 1000 milliseconds.
} catch (InterruptedExceptionie) {
System.out.println(ie.getMessage());} }
}public static void main(String[] args) {
// Create two objects to represent two tasks.MyThread th1 = new MyThread("Cut the
ticket"); // Fanning task
MyThread th2 = new MyThread("Show your seat number"); // Show seat number task
// Create two objects of Thread class and pass two MyThread objects as parameters to
the constructor of Thread class.
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th2); // Start the threads.
t1.start();
t2.start();}}
Output
Cut the ticket:1
Show your seat number:1
Cut the ticket:2
Show your seat number:2
Cut the ticket:3
Show your seat number:3
Cut the ticket:4
Show your seat number:4
Cut the ticket:5
Show your seat number:5
Multiple Threads acting on Single object.

It is also possible to create two or more threads on a single object, Let's create a Java
program in which three threads will share the same object (same ron() method).

Program code:

public class MultipleThread implements Runnable {


String task;
MultipleThread(String task) {
this.task = task;}
public void run() {
for (inti = 1; i<= 5; i++) {
System.out.println(task + ":" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();}} }
public static void main(String[] args) {
Thread nThread = Thread.currentThread();
System.out.println("Name of thread: " + nThread.getName());
// Printing the name of the current thread
// Multiple child threads acting on single object.
MultipleThreadmt = new MultipleThread("Hello Java");
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
Thread t3 = new Thread(mt);
t1.start();
t2.start();
t3.start(); // Waiting for all threads to finish
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
} // Printing the number of active threads
int count = Thread.activeCount();
System.out.println("No of active threads: " + count);}}
Output
Name of thread: main
Hello Java:1
Hello Java:1
Hello Java:1
Hello Java:2
Hello Java:2
Hello Java:2
Hello Java:3
Hello Java:3
Hello Java:3
Hello Java:4
Hello Java:4
Hello Java:4
Hello Java:5
Hello Java:5
Hello Java:5
No of active threads: 1
4.12 ILLUSTRATE THREAD PRIORITIES IN MULTIPLE THREADS WITH AN EXAMPLE:

Java Thread Priority in Multithreading.

1. In the situation of multi-threading, a thread scheduler assigns threads to specific


processes based on their priority.

2. A java thread comes with a pre-assigned priority.

3.In addition to this, the java virtual machine can also assign priority to threads or
explicitly given by the programmers. The range of values for the priority of a thread lies
between 1 and 10 (inclusive).

4.The three static variables associated with priority are

- MAX_PRIORITY The maximum priority that a thread has, whose default value is 10.

- NORM _ PRIORITY The default priority that a thread has, whose default value is 5.

5.The 'getPriority()' method in Java helps in returning the priority of the thread bound as
value to it.

6.The 'setPriority()' method changes the priority value of a given thread. It throws the
IllegalArgumentException when the thread priority is less than 1 or greater than 10.

Program code:

class Demo extends Thread {


public void run() {
System.out.println("Now, inside the run method"); }
public static void main(String[] args) {
Demo myThr1 = new Demo();
Demo myThr2 = new Demo();
System.out.println("The thread priority of first thread is: " + myThr1.getPriority());
System.out.println("The thread priority of second thread is: " + myThr2.getPriority());
myThr1.setPriority(5);
myThr2.setPriority(3);
System.out.println("The thread priority of first thread is: " + myThr1.getPriority());
System.out.println("The thread priority of second thread is: " + myThr2.getPriority()) ;
System.out.println(Thread.currentThread().getName());
System.out.println("The thread priority of main thread is: "
+Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("The thread priority of main thread is: " +
Thread.currentThread().getPriority());}}
output:
The thread priority of first thread is: 5
The thread priority of second thread is: 5
The thread priority of first thread is: 5
The thread priority of second thread is: 3
main
The thread priority of main thread is: 5
The thread priority of main thread is: 10
4.13 DESCRIBE THE CONCEPT OF SYNCHRONIZATION WITH EXAMPLE PROGRAM:
Java Thread Synchronization.

1.When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issues. For example, if multiple threads try to write within a
same file then they may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another thread might be
closing the same file.

2.So there is a need to synchronize the action of multiple threads and make sure that
only one thread can access the resource at a given point in time. This is implemented
using a concept called monitors.

3.Each object in Java is associated with a monitor, which a thread can lock or unlock.
Only one thread at a time may hold a lock on a monitor.

4.Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks.

5.You keep shared resources within this block.

Following is the general form of the synchronized statement

Syntax:

synchronized(objectidentifier) {

// Access shared variables and other shared resources

Multithreading Example without Synchronization:

Here is a simple example which may or may not print counter value in sequence and
every time we run it, it produces a different result based on CPU availability to a thread.

Program code

classPrintDemo {
public void printCount() {
try {
for (inti = 5; i> 0; i--) { System.out.println("Counter - " + i) }
} catch (Exception e) {
System.out.println("Thread interrupted.");}}
classThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemoPD;ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}public void run() {
PD.printCount();
System.out.println("Thread " + threadName + " exiting.");
} public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();} }
}public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo("Thread-1", PD);
ThreadDemo T2 = new ThreadDemo("Thread-2", PD);
T1.start();
T2.start();
try {
T1.join();
T2.join();
} catch (Exception e) {
System.out.println("Interrupted");}}}

output:
Starting Thread-1
Starting Thread-2
Counter - 5
Counter - 4
Counter - 3
Counter - 2
Counter - 1
Thread Thread-1 exiting.
Counter - 5
Counter - 4
Counter - 3
Counter - 2
Counter - 1
Thread Thread-2 exiting.
Multithreading Example with Synchronization:
Here is the same example which prints counter value in sequence and every time we run
it, it produces the same result.

classPrintDemo {
public void printCount() {
try {
for (inti = 5; i> 0; i--) {
System.out.println("Counter - " + i);}
} catch (Exception e) {
System.out.println("Thread interrupted.");}}}
classThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo(String name, PrintDemopd) {
threadName = name;
PD = pd;
} public void run() {
synchronized (PD) {
PD.printCount();}
System.out.println("Thread " + threadName + " exiting.");
} public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();}}}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo("Thread-1", PD);
ThreadDemo T2 = new ThreadDemo("Thread-2", PD);
T1.start();
T2.start();
try {
T1.join();
T2.join(); } catch (Exception e) {
System.out.println("Interrupted");}}}
output:
Starting Thread-1
Starting Thread-2
Counter - 5
Counter - 4
Counter - 3
Counter - 2
Counter - 1
Thread Thread-1 exiting.
Counter - 5
Counter - 4
Counter - 3
Counter - 2
Counter - 1
Thread Thread-2 exiting.
4.14 EXPLAIN INTER THREAD COMMUNICATION WITH EXAMPLE PROGRAM:
Java Interthread Communication:-

1.If you are aware of interprocess communication then it will be easy for you to
understand interthread communication.

2.Interthread communication is important when you develop an application where two


or more threads exchange some information.

3.There are three simple methods and a little trick which makes thread communication
possible. All the three methods are listed below.

S.NO Method & Description


1 public void wait ()
Causes the current thread to wait until another thread invokes the notify ().
2 public void notify ()
Wakes up a single thread that is waiting on this object's monitor.
3 public void notifyAll ()
Wakes up all the threads that called wait() on the same object.

These methods have been implemented as final methods in Object, so they are available
in all the classes. All three methods can be called only from within a synchronized
context.

Example: This example shows how two threads can communicate using wait() and
notify() method. You can create a complex system using the same concept.

Program code

class Chat {
boolean flag = false;
public synchronized void Question(String msg) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();}}
System.out.println(msg);
flag = true;
notify();}
public synchronized void Answer(String msg) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();}}
System.out.println(msg);
flag = false;
notify(); }}
class T1 implements Runnable {
Chat m;
String[] s1 = { "Hi", "How are you?", "I am also doing fine!" };
public T1(Chat m1) {
this.m = m1;
new Thread(this, "Question").start();
} public void run() {
for (inti = 0; i< s1.length; i++)
m.Question(s1[i]);}}
class T2 implements Runnable {
Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
public T2(Chat m2) {
this.m = m2;
new Thread(this, "Answer").start();}
public void run() {
for (inti = 0; i< s2.length; i++)
m.Answer(s2[i]); }}
classTestThread {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);}}
output:
Hi
Hi
How are you?
I am good, what about you?
I am also doing fine!
Great!
4.15 EXPLAIN DEAD LOCK:
Deadlock in Java:

1.Deadlock in Java is a part of multithreading.

2.Deadlock can occur in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other to release the lock,
the condition is called deadlock

Program code:

public class TestDeadlockExample {


public static void main(String[] args) {
final String resource1 = "ratanjaiswal";
final String resource2 = "vinaljaiswal";
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try {
Thread.sleep(100);
} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2"); }}}};
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try {
Thread.sleep(100);
} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1"); }}}};
t1.start();
t2.start();}}
output:
Thread 1: locked resource 1
Thread 2: locked resource 2
Avoiding deadlock: A solution for a problem is found at its roots. In deadlock it is the
pattern of accessing the resources A and B, is the main issue. To solve the issue we will
have to simply re-order the statements where the code is accessing shared resources.
Program code:

public class DeadlockSolved {


public static void main(String[] args) {
DeadlockSolved test = new DeadlockSolved();
finalresourcel a = test.newresourcel();
final resource2 b = test.new resource2();
Runnable b1 = new Runnable() {
public void run() {
synchronized (b) {
try {
/* Adding delay so that both threads can start trying to lock resources */
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); }
// Thread-1 have resource1 but need resource2 also
synchronized (a) {
System.out.println("In block 1"); }}}};
Runnable b2 = new Runnable() {
public void run() {
synchronized (b) {
// Thread-2 have resource2 but need resource1 also
synchronized (a) {
System.out.println("In block 2");}}}};
new Thread(b1).start();
new Thread(b2).start(); }
private class resourcel {
privateinti = 10;
publicintgetI() {
returni; }
public void setI(inti) {
this.i = i; }}
private class resource2 {
privateinti = 20;
publicintgetI() {
returni;
} public void setI(inti) {
this.i = i; }}}
output:
In block 1
In block 2
How to Avoid Deadlock in Java?
Deadlocks cannot be completely resolved. But we can avoid them by following basic
rules mentioned below:

Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main
reason for a deadlock condition. It normally happens when you give locks to multiple
threads.

Avoid Unnecessary Locks: The locks should be given to the important threads. Giving
locks to the unnecessary threads that cause the deadlock condition.

Using Thread Join: A deadlock usually happens when one thread is waiting for the other
to finish. In this case, we can use join with a maximum time that a thread will take.

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