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

java 3rd unit@2

The document provides an overview of Exception Handling in Java, explaining its importance in maintaining the normal flow of applications by managing runtime errors. It discusses the types of exceptions (checked, unchecked, and errors), the keywords used in exception handling (try, catch, finally, throw, throws), and includes examples to illustrate various scenarios. Additionally, it covers the concept of multi-catch blocks and the internal workings of try-catch mechanisms in Java.

Uploaded by

pothusrikar94
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java 3rd unit@2

The document provides an overview of Exception Handling in Java, explaining its importance in maintaining the normal flow of applications by managing runtime errors. It discusses the types of exceptions (checked, unchecked, and errors), the keywords used in exception handling (try, catch, finally, throw, throws), and includes examples to illustrate various scenarios. Additionally, it covers the concept of multi-catch blocks and the internal workings of try-catch mechanisms in Java.

Uploaded by

pothusrikar94
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/ 34

JAVA Unit-3 CMR Technical Campus

Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.

Exception is an abnormal condition. In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.

Advantage
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception handling.

• Separating Error-Handling code from “regular” business logic code


• Propagating errors up the call stack
• Grouping and differentiating error types

Example:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest
of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception
handling, the rest of the statement will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error.

A hierarchy of Java Exception classes are given below:

1 N Bhaskar
JAVA Unit-3 CMR Technical Campus

2 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions
are checked at compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.
Keyword Description

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

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 important 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 doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

General form:
try { … }
catch(Exception1 ex1) { … }
catch(Exception2 ex2) { … }

finally { … }

where:
1) try { … } is the block of code to monitor for exceptions
2) catch(Exception ex) { … } is exception handler for the exception Exception
3) finally { … } is the block of code to execute before the try block ends

3 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Example:
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e) //catch(Exception e)
7. {System.out.println(e);}
8. //rest code of the program
9. System.out.println("rest of the code...");
10. } }

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws
a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException. Suppose I have
a string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Termination vs. resumption


There are two basic models in exception-handling theory. In termination (which is what
C++ supports) you assume the error is so critical there’s no way to get back to where the
exception occurred. Whoever threw the exception decided there was no way to salvage
the situation, and they don’t want to come back.

The alternative is called resumption. It means the exception handler is expected to do


something to rectify the situation, and then the faulting function is retried, presuming
success the second time. If you want resumption, you still hope to continue execution
after the exception is handled, so your exception is more like a function call – which is
4 N Bhaskar
JAVA Unit-3 CMR Technical Campus
how you should set up situations in C++ where you want resumption-like behavior (that
is, don’t throw an exception; call a function that fixes the problem). Alternatively, place
your try block inside a while loop that keeps reentering the try block until the result is
satisfactory.

Historically, programmers using operating systems that supported resumptive exception


handling eventually ended up using termination-like code and skipping resumption. So
although resumption sounds attractive at first, it seems it isn’t quite so useful in practice.
One reason may be the distance that can occur between the exception and its handler;
it’s one thing to terminate to a handler that’s far away, but to jump to that handler and
then back again may be too conceptually difficult for large systems where the exception
can be generated from many points.

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 of try block, the rest of the block code will not execute.
So, it is recommended not to keeping the code in try block that will not throw an exception. Java try block
must be followed by either catch or finally block.

Syntax: Java try-catch


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Syntax: try-finally block


1. try{
2. //code that may throw an exception
3. }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:

o Prints out exception description.


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

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

5 N Bhaskar
JAVA Unit-3 CMR Technical Campus

Example:
Problem without exception handling
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8. } }

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case, the rest of
the code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling


1. public class TryCatchExample2 {
2. public static void main(String[] args) {
3. try
4. {
5. int data=50/0; //may throw exception
6. }
7. //handling the exception
8. catch(ArithmeticException e)
9. {
10. System.out.println(e);
11. }
12. System.out.println("rest of the code");
13. } }

Output:
java.lang.ArithmeticException: / by zero
rest of the code
Now, as displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.

6 N Bhaskar
JAVA Unit-3 CMR Technical Campus

we also kept the code in a try block that will not throw an exception.
1. public class TryCatchExample3 {
2. public static void main(String[] args) {
3. try
4. {
5. int data=50/0; //may throw exception
6. // if exception occurs, the remaining statement will not exceute
7. System.out.println("rest of the code");
8. }
9. // handling the exception
10. catch(ArithmeticException e)
11. {
12. System.out.println(e);
13. } } }

Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.

we handle the exception using the parent class exception.


1. public class TryCatchExample4 {
2. public static void main(String[] args) {
3. try
4. {
5. int data=50/0; //may throw exception
6. }
7. // handling the exception by using Exception class
8. catch(Exception e)
9. {
10. System.out.println(e);
11. }
12. System.out.println("rest of the code");
13. } }

Output:
java.lang.ArithmeticException: / by zero
rest of the code

an example to print a custom message on exception.


1. public class TryCatchExample5 {
2. public static void main(String[] args) {
3. try
4. {
5. int data=50/0; //may throw exception
6. }
7. // handling the exception
8. catch(Exception e)
9. {
10. // displaying the custom message
11. System.out.println("Can't divided by zero");
12. } } }

Output:
Can't divided by zero

an example to resolve the exception in a catch block.


1. public class TryCatchExample6 {
2. public static void main(String[] args) {
3. int i=50;
4. int j=0;
5. int data;

7 N Bhaskar
JAVA Unit-3 CMR Technical Campus
6. try
7. {
8. data=i/j; //may throw exception
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // resolving the exception in catch block
14. System.out.println(i/(j+2));
15. } } }

Output:
25

In this example, along with try block, we also enclose exception code in a catch
block.
1. public class TryCatchExample7 {
2. public static void main(String[] args) {
3. try
4. {
5. int data1=50/0; //may throw exception
6. }
7. // handling the exception
8. catch(Exception e)
9. {
10. // generating the exception in catch block
11. int data2=50/0; //may throw exception
12. }
13. System.out.println("rest of the code");
14. } }

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the exception code. So, enclose exception code within
a try block and use catch block only to handle the exceptions.

In this example, we handle the generated exception (Arithmetic Exception) with


a different type of exception class (ArrayIndexOutOfBoundsException).
1. public class TryCatchExample8 {
2. public static void main(String[] args) {
3. try
4. {
5. int data=50/0; //may throw exception
6. }
7. // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
8. catch(ArrayIndexOutOfBoundsException e)
9. {
10. System.out.println(e);
11. }
12. System.out.println("rest of the code");
13. } }

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

an example to handle unchecked exception.


1. public class TryCatchExample9 {
2. public static void main(String[] args) {
3. try
4. {
5. int arr[]= {1,3,5,7};
6. System.out.println(arr[10]); //may throw exception
7. }

8 N Bhaskar
JAVA Unit-3 CMR Technical Campus
8. // handling the array exception
9. catch(ArrayIndexOutOfBoundsException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. } }

Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code

an example to handle checked exception.


1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3. public class TryCatchExample10 {
4. public static void main(String[] args) {
5. PrintWriter pw;
6. try {
7. pw = new PrintWriter("jtp.txt"); //may throw exception
8. pw.println("saved");
9. }
10. // providing the checked exception handler
11. catch (FileNotFoundException e) {
12. System.out.println(e);
13. }
14. System.out.println("File saved successfully");
15. } }

Output:
File saved successfully

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.

Points
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Example:
1. public class MultipleCatchBlock1 {
2. public static void main(String[] args) {
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e)
8. {
9. System.out.println("Arithmetic Exception occurs");
10. }
11. catch(ArrayIndexOutOfBoundsException e)
12. {
13. System.out.println("ArrayIndexOutOfBounds Exception occurs");
14. }
15. catch(Exception e)
16. {
17. System.out.println("Parent Exception occurs");
18. }
19. System.out.println("rest of the code");
20. } }
9 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Output:
Arithmetic Exception occurs
rest of the code

Example:
1. public class MultipleCatchBlock2 {
2. public static void main(String[] args) {
3. try{
4. int a[]=new int[5];
5. System.out.println(a[10]);
6. }
7. catch(ArithmeticException e)
8. {
9. System.out.println("Arithmetic Exception occurs");
10. }
11. catch(ArrayIndexOutOfBoundsException e)
12. {
13. System.out.println("ArrayIndexOutOfBounds Exception occurs");
14. }
15. catch(Exception e)
16. {
17. System.out.println("Parent Exception occurs");
18. }
19. System.out.println("rest of the code");
20. } }

Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code

In this example, try block contains two exceptions. But at a time only one exception occurs and its
corresponding catch block is invoked.
1. public class MultipleCatchBlock3 {
2. public static void main(String[] args) {
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. System.out.println(a[10]);
7. }
8. catch(ArithmeticException e)
9. {
10. System.out.println("Arithmetic Exception occurs");
11. }
12. catch(ArrayIndexOutOfBoundsException e)
13. {
14. System.out.println("ArrayIndexOutOfBounds Exception occurs");
15. }
16. catch(Exception e)
17. {
18. System.out.println("Parent Exception occurs");
19. }
20. System.out.println("rest of the code");
21. } }

Output:
Arithmetic Exception occurs
rest of the code

In this example, we generate NullPointerException, but didn't provide the corresponding exception type. In
such case, the catch block containing the parent exception class Exception will invoked.
1. public class MultipleCatchBlock4 {
2. public static void main(String[] args) {
3. try{
4. String s=null;
5. System.out.println(s.length());

10 N Bhaskar
JAVA Unit-3 CMR Technical Campus
6. }
7. catch(ArithmeticException e)
8. {
9. System.out.println("Arithmetic Exception occurs");
10. }
11. catch(ArrayIndexOutOfBoundsException e)
12. {
13. System.out.println("ArrayIndexOutOfBounds Exception occurs");
14. }
15. catch(Exception e)
16. {
17. System.out.println("Parent Exception occurs");
18. }
19. System.out.println("rest of the code");
20. } }

Output:
Parent Exception occurs
rest of the code

to handle the exception without maintaining the order of exceptions (i.e. from most specific to most
general).
1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }

Output:
Compile-time error

Nested try block


The try block within a try block is known as nested try block in java. Sometimes a situation may arise where
a part of a block may cause one error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.

Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....

11 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Example:
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13. System.out.println("other statement);
14. }catch(Exception e){System.out.println("handeled");}
15. System.out.println("normal flow..");
16. } }

Output:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..

finally block
Java finally block is a block that is used to execute important code such as closing connection, stream
etc. Java finally block is always executed whether exception is handled or not. Java finally block follows try
or catch block.

Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
any).

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

Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
12 N Bhaskar
JAVA Unit-3 CMR Technical Campus
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. } }

Output:5
finally block is always executed
rest of the code...

Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. } }

Output:finally block is always executed


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

Case 3
Let's see the java finally example where exception occurs and handled.
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. } }

Output:Exception in thread main 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 program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).

throw keyword
The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked
exception in java by throw keyword. The throw keyword is mainly used to throw custom exception.
The syntax of java throw keyword is given below.
throw exception;

example of throw IOException.


throw new IOException("sorry device error”);

13 N Bhaskar
JAVA Unit-3 CMR Technical Campus
In this example, we have created the validate method that takes integer value as a parameter. If the age
is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
1. public class TestThrow1{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. } }

Output:
Exception in thread main java.lang.ArithmeticException:not valid

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to
the previous method, If not caught there, the exception again drops down to the previous method, and so
on until they are caught or until they reach the very bottom of the call stack. This is called exception
propagation.

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Example:
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. } }

Output:exception handled
normal flow...

In the above example exception occurs in m() method where it is not handled,so it is propagated to previous
n() method where it is not handled, again it is propagated to p() method where exception is handled.

14 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Exception can be handled in any method in call stack either in main() method,p() method,n() method or
m() method.

Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Example:
1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. } }

Output:Compile Time Error

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 normal flow 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 performing check up before
the code being used.

Syntax:
1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Checked exceptions only declared because:


o unchecked Exception: under your control so correct your code.
o error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.

Advantages:
o Now Checked Exception can be propagated (forwarded in call stack).
o It provides information to the caller of the method about the exception.

the example of java throws clause which describes that checked exceptions can be propagated by throws
keyword.
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
15 N Bhaskar
JAVA Unit-3 CMR Technical Campus
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. } }

Output:
exception handled
normal flow...

Rule: If you are calling a method that declares an exception, you must either caught or declare the
exception.

There are two cases:


1. Case1: You caught the exception i.e. handle the exception using try/catch.
2. Case2: You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception


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

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. } }

Output:exception handled
normal flow...

Case2: You declare the exception


o A)In case you declare the exception, if exception does not occur, the code will be executed fine.
o B)In case you declare the exception if exception occures, an exception will be thrown at runtime
because throws does not handle the exception.

A)Program if exception does not occur


1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. } }
6. class Testthrows3{
7. public static void main(String args[])throws IOException{//declare exception
8. M m=new M();
9. m.method();
10. System.out.println("normal flow...");
11. } }

16 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Output:device operation performed
normal flow...

B)Program if exception occurs


1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. } }
6. class Testthrows4{
7. public static void main(String args[])throws IOException{//declare exception
8. M m=new M();
9. m.method();
10. System.out.println("normal flow...");
11. } }

Output:
Exception in thread "main" java.io.IOException: device error
at M.method(Testthrows4.java:4)
at Testthrows4.main(Testthrows4.java:10)

Java Built In Exceptions


Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type RuntimeException. Since
java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException
are automatically available.

Java defines several other types of exceptions that relate to its various class libraries. Following is the list
of Java Unchecked RuntimeException.

Exception Meaning

ArithmeticException Arithmetic error, such as divide-by-zero

ArrayIndexOutOfBoundsException Array index is out-of-bounds

ArrayStoreException Assignment to an array element of an incompatible type

ClassCastException Invalid cast

EnumConstantNotPresentException An attempt is made to use an undefined enumeration value

IllegalArgumentException Illegal argument used to invoke a method

IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread

IllegalStateException Environment or application is in incorrect state

IllegalThreadStateException Requested operation not compatible with current thread state

IndexOutOfBoundsException Some type of index is out-of-bounds

NegativeArraySizeException Array created with a negative size

NullPointerException Invalid use of a null reference

NumberFormatException Invalid conversion of a string to a numeric format

SecurityException Attempt to violate security

StringIndexOutOfBounds Attempt to index outside the bounds of a string

17 N Bhaskar
JAVA Unit-3 CMR Technical Campus
TypeNotPresentException Type not found

UnsupportedOperationException An unsupported operation was encountered

Following is the list of Java Checked Exceptions Defined in java.lang.


Exception Meaning

ClassNotFoundException Class not found

CloneNotSupportedException Attempt to clone an object that doesn't implement the Cloneable interface

IllegalAccessException Access to a class is denied

InstantiationException Attempt to create an object of an abstract class or interface

InterruptedException One thread has been interrupted by another thread

NoSuchFieldException A requested field does not exist

NoSuchMethodException A requested method doesn't exist

ReflectiveOperationException Superclass of reflection-related exceptions

ExceptionHandling with MethodOverriding in Java


There are many rules if we talk about methodoverriding with exception handling.
The Rules are as follows:
o If the superclass method does not declare an exception
o If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but it can declare unchecked exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.

If the superclass method does not declare an exception

1) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.

1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5. class TestExceptionChild extends Parent{
6. void msg()throws IOException{
7. System.out.println("TestExceptionChild");
8. }
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild();
11. p.msg();
12. } }

Output:Compile Time Error

18 N Bhaskar
JAVA Unit-3 CMR Technical Campus

2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.

1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5. class TestExceptionChild1 extends Parent{
6. void msg()throws ArithmeticException{
7. System.out.println("child");
8. }
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild1();
11. p.msg();
12. } }

Output:child

If the superclass method declares an exception

1) Rule: If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent exception


1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5. class TestExceptionChild2 extends Parent{
6. void msg()throws Exception{System.out.println("child");}
7. public static void main(String args[]){
8. Parent p=new TestExceptionChild2();
9. try{
10. p.msg();
11. }catch(Exception e){}
12. } }

Output:Compile Time Error

Example in case subclass overridden method declares same exception


1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5. class TestExceptionChild3 extends Parent{
6. void msg()throws Exception{System.out.println("child");}
7. public static void main(String args[]){
8. Parent p=new TestExceptionChild3();
9. try{
10. p.msg();
11. }catch(Exception e){}
12. } }

Output:child

19 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Example in case subclass overridden method declares subclass exception
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5. class TestExceptionChild4 extends Parent{
6. void msg()throws ArithmeticException{System.out.println("child");}
7. public static void main(String args[]){
8. Parent p=new TestExceptionChild4();
9. try{
10. p.msg();
11. }catch(Exception e){}
12. } }

Output:child

Example in case subclass overridden method declares no exception


1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5. class TestExceptionChild5 extends Parent{
6. void msg(){System.out.println("child");}
7. public static void main(String args[]){
8. Parent p=new TestExceptionChild5();
9. try{
10. p.msg();
11. }catch(Exception e){}
12. } }

Output:child

Java Custom Exception


If you are creating your own Exception that is known as custom exception or user-defined exception. Java
custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.
a simple example of java custom exception.

1. class InvalidAgeException extends Exception{


2. InvalidAgeException(String s){
3. super(s);
4. } }

1. class TestCustomException1{
2. static void validate(int age)throws InvalidAgeException{
3. if(age<18)
4. throw new InvalidAgeException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. try{
10. validate(13);
11. }catch(Exception m){System.out.println("Exception occured: "+m);}
12. System.out.println("rest of the code...");
13. } }

Output:Exception occured: InvalidAgeException:not valid


rest of the code...

20 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Multithreading
Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading,
both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They
don't allocate separate memory area so saves memory, and context-switching between the threads takes
less time than process.

Advantages:
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:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a separate memory
area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Note: At least one process is required for each thread.

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.

As shown in the above figure, a thread is executed inside the process. There is context-switching between
the threads. There can be multiple processes inside the OS, and one process can have multiple threads.

21 N Bhaskar
JAVA Unit-3 CMR Technical Campus

Note: At a time one thread is executed only.

Java Thread class


Java provides Thread class to achieve thread programming. Thread class provides constructors and
methods to create and perform operations on a thread. Thread class extends Object class and implements
Runnable interface.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in
java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected
it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.

create thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.
22 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread. JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Example:
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. } }

Output:thread is running...

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:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
Example:
1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
23 N Bhaskar
JAVA Unit-3 CMR Technical Campus
5. public static void main(String args[]){
6. Multi3 m1=new Multi3();
7. Thread t1 =new Thread(m1);
8. t1.start();
9. } }

Output:thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread object. So
you need to explicitly create Thread class object. We are passing the object of your class that implements
Runnable so that your class run() method may execute.

Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority (known as preemptive scheduling). But
it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

Thread class defines following 3 constants:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.

Get and Set Thread Priority:


1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread
to the value newPriority. This method throws IllegalArgumentException if value of parameter newPriority goes beyond
minimum(1) and maximum(10) limit.

Example:
1. class TestMultiPriority1 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5. }
6. public static void main(String args[]){
7. TestMultiPriority1 m1=new TestMultiPriority1();
8. TestMultiPriority1 m2=new TestMultiPriority1();
9. m1.setPriority(Thread.MIN_PRIORITY);
10. m2.setPriority(Thread.MAX_PRIORITY);
11. m1.start();
12. m2.start();
13. } }

Output:1
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:10
running thread priority is:1

Example:
// Java program to demonstrate getPriority() and setPriority()
import java.lang.*;

class ThreadDemo extends Thread


{
public void run()
{
System.out.println("Inside run method");
}

24 N Bhaskar
JAVA Unit-3 CMR Technical Campus
public static void main(String[]args)
{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();

System.out.println("t1 thread priority : " +


t1.getPriority()); // Default 5
System.out.println("t2 thread priority : " +
t2.getPriority()); // Default 5
System.out.println("t3 thread priority : " +
t3.getPriority()); // Default 5

t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// t3.setPriority(21); will throw IllegalArgumentException


System.out.println("t1 thread priority : " +
t1.getPriority()); //2
System.out.println("t2 thread priority : " +
t2.getPriority()); //5
System.out.println("t3 thread priority : " +
t3.getPriority());//8

// Main thread
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());

// Main thread priority is set to 10


Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());
}
}
Output:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Main thread priority : 5
Main thread priority : 10

Note:
• Thread with highest priority will get execution chance prior to other threads. Suppose there are 3
threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will execute first based on maximum
priority 6 after that t1 will execute and then t3.
• Default priority for main thread is always 5, it can be changed later. Default priority for all other
threads depends on the priority of parent thread.

Example:
// Java program to demonstrat ethat a child thread
// gets same priority as parent
import java.lang.*;

class ThreadDemo extends Thread


{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
// main thread priority is 6 now
Thread.currentThread().setPriority(6);
25 N Bhaskar
JAVA Unit-3 CMR Technical Campus
System.out.println("main thread priority : " +
Thread.currentThread().getPriority());

ThreadDemo t1 = new ThreadDemo();

// t1 thread is child of main thread


// so t1 thread will also have priority 6.
System.out.println("t1 thread priority : "
+ t1.getPriority());
}
}
Output:
Main thread priority : 6
t1 thread priority : 6
• If two threads have same priority then we can’t expect which thread will execute first. It depends on
thread scheduler’s algorithm(Round-Robin, First Come First Serve, etc)
• If we are using thread priority for thread scheduling then we should always keep in mind that
underlying platform should provide support for scheduling based on thread priority.

Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Advantage:
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. 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.
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. This can be done
by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization

Lock:
Synchronization is built around an internal entity known as the lock or monitor. Every object has an 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.

without Synchronization
there is no synchronization, so output is inconsistent. Let's see the example:
1. class Table{
2. void printTable(int n){//method not synchronized

26 N Bhaskar
JAVA Unit-3 CMR Technical Campus
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. } }}
9. class MyThread1 extends Thread{
10. Table t;
11. MyThread1(Table t){
12. this.t=t;
13. }
14. public void run(){
15. t.printTable(5);
16. } }
17. class MyThread2 extends Thread{
18. Table t;
19. MyThread2(Table t){
20. this.t=t;
21. }
22. public void run(){
23. t.printTable(100);
24. } }
25. class TestSynchronization1{
26. public static void main(String args[]){
27. Table obj = new Table();//only one object
28. MyThread1 t1=new MyThread1(obj);
29. MyThread2 t2=new MyThread2(obj);
30. t1.start();
31. t2.start();
32. } }

Output: 5
100
10
200
15
300
20
400
25
500

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.
1. //example of java synchronized method
2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. } } }
10. class MyThread1 extends Thread{
11.Table t;
12.MyThread1(Table t){
13.this.t=t;
14.}
15.public void run(){
16.t.printTable(5);
17.} }
18.class MyThread2 extends Thread{

27 N Bhaskar
JAVA Unit-3 CMR Technical Campus
19.Table t;
20.MyThread2(Table t){
21.this.t=t;
22.}
23.public void run(){
24.t.printTable(100);
25.} }
26. public class TestSynchronization2{
27.public static void main(String args[]){
28.Table obj = new Table();//only one object
29.MyThread1 t1=new MyThread1(obj);
30.MyThread2 t2=new MyThread2(obj);
31.t1.start();
32.t2.start();
33.} }

Output: 5
10
15
20
25
100
200
300
400
500
synchronized method by using annonymous class
In this program, we have created the two threads by annonymous class, so less coding is required.
1. //Program of synchronized method by using annonymous class
2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. } }}
10.public class TestSynchronization3{
11.public static void main(String args[]){
12.final Table obj = new Table();//only one object
13.Thread t1=new Thread(){
14.public void run(){
15.obj.printTable(5);
16.} };
17.Thread t2=new Thread(){
18.public void run(){
19.obj.printTable(100);
20.} };
21.t1.start();
22.t2.start();
23.} }

Output: 5
10
15
20
25
100
200
300
400
500

Synchronized Block
Synchronized block can be used to perform synchronization on any specific resource of the method. Suppose
you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use
synchronized block.
28 N Bhaskar
JAVA Unit-3 CMR Technical Campus
If you put all the codes of the method in the synchronized block, it will work same as the synchronized
method.

Points to remember
o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.

Syntax
1. synchronized (object reference expression) {
2. //code block
3. }

Example:
1. class Table{
2. void printTable(int n){
3. synchronized(this){//synchronized block
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
11. }//end of the method
12. }
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. } }
21. class MyThread2 extends Thread{
22. Table t;
23. MyThread2(Table t){
24. this.t=t;
25. }
26. public void run(){
27. t.printTable(100);
28. } }
29. public class TestSynchronizedBlock1{
30. public static void main(String args[]){
31. Table obj = new Table();//only one object
32. MyThread1 t1=new MyThread1(obj);
33. MyThread2 t2=new MyThread2(obj);
34. t1.start();
35. t2.start();
36. } }

Output:5
10
15
20
25
100
200
300
400
500

using annonymous class:


1. class Table{
2. void printTable(int n){
3. synchronized(this){//synchronized block
4. for(int i=1;i<=5;i++){

29 N Bhaskar
JAVA Unit-3 CMR Technical Campus
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
11.}//end of the method
12.}
13.public class TestSynchronizedBlock2{
14.public static void main(String args[]){
15.final Table obj = new Table();//only one object
16.Thread t1=new Thread(){
17.public void run(){
18.obj.printTable(5);
19.} };
20.Thread t2=new Thread(){
21.public void run(){
22.obj.printTable(100);
23.} };
24.t1.start();
25.t2.start();
26. } }

Output:5
10
15
20
25
100
200
300
400
500

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

Problem without static synchronization


Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of
synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4
because t1 and t2 both refers to a common object that have a single lock. But there can be interference
between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock. I want no
interference between t1 and t3 or t2 and t4. Static synchronization solves this problem.

1. class Table{
2. synchronized static void printTable(int n){
3. for(int i=1;i<=10;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){}
8. } }}
9. class MyThread1 extends Thread{
10. public void run(){
11. Table.printTable(1);

30 N Bhaskar
JAVA Unit-3 CMR Technical Campus
12. } }
13. class MyThread2 extends Thread{
14. public void run(){
15. Table.printTable(10);
16. } }
17. class MyThread3 extends Thread{
18. public void run(){
19. Table.printTable(100);
20. } }
21. class MyThread4 extends Thread{
22. public void run(){
23. Table.printTable(1000);
24. } }
25. public class TestSynchronization4{
26. public static void main(String t[]){
27. MyThread1 t1=new MyThread1();
28. MyThread2 t2=new MyThread2();
29. MyThread3 t3=new MyThread3();
30. MyThread4 t4=new MyThread4();
31. t1.start();
32. t2.start();
33. t3.start();
34. t4.start();
35. } }

Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
static synchronization by annonymous class
1. class Table{
2. synchronized static void printTable(int n){
3. for(int i=1;i<=10;i++){
31 N Bhaskar
JAVA Unit-3 CMR Technical Campus
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){}
8. } }}
9. public class TestSynchronization5 {
10. public static void main(String[] args) {
11. Thread t1=new Thread(){
12. public void run(){
13. Table.printTable(1);
14. } };
15. Thread t2=new Thread(){
16. public void run(){
17. Table.printTable(10);
18. } };
19. Thread t3=new Thread(){
20. public void run(){
21. Table.printTable(100);
22. } };
23. Thread t4=new Thread(){
24. public void run(){
25. Table.printTable(1000);
26. } };
27. t1.start();
28. t2.start();
29. t3.start();
30. t4.start();
31. } }

Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

32 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Inter-thread communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is
implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()

1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method
or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.

2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax:
public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()

Points:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the
lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

33 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Note: wait(), notify() and notifyAll() methods are defined in Object class not Thread class because they
are related to lock and object has a lock.

Difference between wait and sleep

wait() sleep()

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

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

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

Example:
1. class Customer{
2. int amount=10000;
3. synchronized void withdraw(int amount){
4. System.out.println("going to withdraw...");
5. if(this.amount<amount){
6. System.out.println("Less balance; waiting for deposit...");
7. try{wait();}catch(Exception e){}
8. }
9. this.amount-=amount;
10. System.out.println("withdraw completed...");
11. }
12. synchronized void deposit(int amount){
13. System.out.println("going to deposit...");
14. this.amount+=amount;
15. System.out.println("deposit completed... ");
16. notify();
17. } }
18. class Test{
19. public static void main(String args[]){
20. final Customer c=new Customer();
21. new Thread(){
22. public void run(){c.withdraw(15000);}
23. }.start();
24. new Thread(){
25. public void run(){c.deposit(10000);}
26. }.start();
27. }}

Output: going to withdraw...


Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

34 N Bhaskar

You might also like