java 3rd unit@2
java 3rd unit@2
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.
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.
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.
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.
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:
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.
The catch block must be used after the try block only. You can use multiple catch block with a single try
block.
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.
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.
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Output:
Can't divided by zero
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.
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
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
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
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. } }
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. } }
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;
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.
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. } }
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. }
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.
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...
16 N Bhaskar
JAVA Unit-3 CMR Technical Campus
Output:device operation performed
normal flow...
Output:
Exception in thread "main" java.io.IOException: device error
at M.method(Testthrows4.java:4)
at Testthrows4.main(Testthrows4.java:10)
Java defines several other types of exceptions that relate to its various class libraries. Following is the list
of Java Unchecked RuntimeException.
Exception Meaning
17 N Bhaskar
JAVA Unit-3 CMR Technical Campus
TypeNotPresentException Type not found
CloneNotSupportedException Attempt to clone an object that doesn't implement the Cloneable interface
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. } }
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
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.
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
Output:child
By the help of custom exception, you can have your own exception and message.
a simple example of java custom exception.
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. } }
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)
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
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)
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().
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.
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
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.*;
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();
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// Main thread
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());
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.*;
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.
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
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.
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(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.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
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. }}
34 N Bhaskar