UNIT 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

UNIT 4

Exception Handling in Java


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

In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and
unchecked exceptions.

Dictionary Meaning: 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.

Backward Skip 10sPlay Video Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions

In Java, exception is an event that occurs during the execution of a program and disrupts the normal flow of
the program's instructions. Bugs or errors that we don't want and restrict our program's normal execution of
code are referred to as exceptions. In this section, we will focus on the types of exceptions in Java and the
differences between the two.

Exceptions can be categorized into two ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
3. Error

4.
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception. These exceptions
are able to define the error situation so that we can understand the reason of getting this error. It can be
categorized into two broad categories, i.e., checked exceptions and unchecked exception.

Checked Exception
Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-
time by the compiler. The compiler ensures whether the programmer handles the exception or not. The
programmer should have to handle the exception; otherwise, the system has shown a compilation error.

CheckedExceptionExample.java

1. import java.io.*;
2. class CheckedExceptionExample {
3. public static void main(String args[]) {
4. FileInputStream file_data = null;
5. file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt");
6. int m;
7. while(( m = file_data.read() ) != -1) {
8. System.out.print((char)m);
9. }
10. file_data.close();
11. }
12. }
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in
exception. These exceptions are able to define the error situation so that we can
understand the reason of getting this error. It can be categorized into two broad
categories, i.e., checked exceptions and unchecked exception.

Checked Exception

Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler. The compiler ensures whether the
programmer handles the exception or not. The programmer should have to handle the
exception; otherwise, the system has shown a compilation error.

In the above code, we are trying to read the Hello.txt file and display its data or content on the screen. The
program throws the following exceptions:

1. The FileInputStream(File filename) constructor throws the FileNotFoundException that is checked


exception.
2. The read() method of the FileInputStream class throws the IOException.
3. The close() method also throws the IOException.

Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these
exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we
didn't handle or declare it, the program would not give a compilation error. Usually, it occurs when the user
provides bad data during the interaction with the program.

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

1. class UncheckedExceptionExample1 {
2. public static void main(String args[])
3. {
4. int postive = 35;
5. int zero = 0;
6. int result = positive/zero;
7. //Give Unchecked Exception here.
8. System.out.println(result);
9. }
10. }
In the above program, we have divided 35 by 0. The code would be compiled successfully, but it will throw
an ArithmeticException error at runtime. On dividing a number by 0 throws the divide by zero exception
that is a uncheck exception.

Description:
In the above code, we have created two classes,
i.e., UserDefinedException and NewException. The UserDefinedException has our main
method, and the NewException class is our user-defined exception class, which
extends exception. In the NewException class, we create a variable x of type integer and assign
a value to it in the constructor. After assigning a value to that variable, we return the exception
message.
In the UserDefinedException class, we have added a try-catch block. In the try section, we
throw the exception, i.e., NewException and pass an integer to it. The value will be passed to
the NewException class and return a message. We catch that message in the catch block and
show it on the screen.

Difference Between Checked and Unchecked Exception


S.No Checked Exception Unchecked Exception

1. These exceptions are checked at compile time. These exceptions These exceptions are just opposite to the ch
are handled at compile time too. exceptions are not checked and handled at comp

2. These exceptions are direct subclasses of exception but not They are the direct subclasses of the RuntimeExc
extended from RuntimeException class.

3. The code gives a compilation error in the case when a method The code compiles without any error because t
throws a checked exception. The compiler is not able to handle the notice of the compiler. These exceptions are th
exception on its own. errors in programming logic.

4. These exceptions mostly occur when the probability of failure is These exceptions occur mostly due to programm
too high.

5. Common checked exceptions include IOException, Common unchecked exceptions includ


DataAccessException, InterruptedException, etc. InvalidClassException, NullPointerException, etc

6. These exceptions are propagated using the throws keyword. These are automatically propagated.

7. It is required to provide the try-catch and try-finally block to In the case of unchecked exception it is not mand
handle the checked exception.

Bugs or errors that we don't want and restrict the normal execution of the programs are referred
to as exceptions.
ArithmeticException, ArrayIndexOutOfBoundExceptions, ClassNotFoundExceptions etc. are come in the
category of Built-in Exception. Sometimes, the built-in exceptions are not sufficient to explain or describe
certain situations. For describing these situations, we have to create our own exceptions by creating an
exception class as a subclass of the Exception class. These types of exceptions come in the category
of User-Defined Exception.
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.

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

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError
etc.

Java Exception Keywords


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

Keyword Description

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

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

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

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

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the me
exception. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the
exception.
JavaExceptionExample.java

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){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }

Java try and catch


The try statement allows you to define a block of code to be tested for errors while it is being
executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.

The try and catch keywords come in pairs:

SyntaxGet your own Java Server


try {

// Block of code to try

catch(Exception e) {

// Block of code to handle errors

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {

public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]); // error!

}
}

The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute some code to handle
it:

Example
public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

The output will be:

Something went wrong.

Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
public class Main {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {

System.out.println("The 'try catch' is finished.");

The output will be:

Something went wrong.


The 'try catch' is finished.

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword throw the exception
explicitly from a method or a block of code whereas the throws keyword is used in signature of the method.

There are many differences between throw and throws keywords. A list of differences between throw and
throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is used throw an Java throws keywo


exception explicitly in the code, inside the signature to decla
function or the block of code. might be thrown b
execution of the cod
2. Type of exception Using throw keyword, we Using throws keyword, we can declare both
can only propagate unchecked exception i.e., checked and unchecked exceptions.
the checked exception cannot be propagated However, the throws keyword can be used to
using throw only. propagate checked exceptions only.

3. Syntax The throw keyword is followed by an instance The throws keywo


of Exception to be thrown. names of Exception

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

5. Internal implementation We are allowed to throw only one exception We can declare m
at a time i.e. we cannot throw multiple throws keyword th
exceptions. method. For ex
IOException, SQLEx

Java throw Example


TestThrow.java

1. public class TestThrow {


2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate square");
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }

Java throws Example


TestThrows.java

1. public class TestThrows {


2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticException {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. System.out.println(obj.divideNum(45, 0));
12. }
13. catch (ArithmeticException e){
14. System.out.println("\nNumber cannot be divided by 0");
15. }
16.
17. System.out.println("Rest of the code..");
18. }
19. }
Output:

Java throw and throws Example


TestThrowAndThrows.java

1. public class TestThrowAndThrows


2. {
3. // defining a user-defined method
4. // which throws ArithmeticException
5. static void method() throws ArithmeticException
6. {
7. System.out.println("Inside the method()");
8. throw new ArithmeticException("throwing ArithmeticException");
9. }
10. //main method
11. public static void main(String args[])
12. {
13. try
14. {
15. method();
16. }
17. catch(ArithmeticException e)
18. {
19. System.out.println("caught in main() method");
20. }
21. }
22. }
PART 2

Multithreading in Java

Multithreading in Java is a process of executing multiple threads simultaneously.

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

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

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

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate
path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

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

Note: At a time one thread is executed only.

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.

Difference between Multitasking and Multithreading in


Operating System
A CPU does both of these tasks, but there is a key distinction between multitasking and multithreading.
While multithreading is essentially a thread-based kind of multitasking, the phrase "multitasking" refers to a
logical extension of the concept of "multiprogramming". On the other hand, multithreading facilitates the
concurrent execution of several threads within a single process, and multitasking allows the CPU to
perform multiple tasks (threads, processes, programs, and tasks).

In this article, you will learn about the difference between multitasking and multithreading in the operating
system. But before discussing the differences, you must know about multitasking and multithreading in the
operating system.

What is Multitasking?
When a single processor (CPU) does many jobs (program, threads, process, task) simultaneously, it is
called multitasking. The CPU switches between these activities often so the user can engage with each
program simultaneously to execute multitasking.

A multitasking operating system allows multiple users to share the system simultaneously. As we've seen,
the CPU switches between tasks quickly; as a result, moving between users takes some time. It puts an
impression on a user that the complete system is focused on him.

When numerous users share a multitasking OS, CPU scheduling and multiprogramming allow each user to
have at least a tiny fraction of the Multitasking OS and at least one application in memory for execution.

Advantages and Disadvantages of Multitasking Operating System


There are various advantages and disadvantages of a multitasking operating system. Some advantages and
disadvantages of a multitasking operating system are as follows:

Advantages

1. The main concept and advantage of MOS is time-sharing. There is no CPU waiting time, and each
task is given an appropriate amount of time.
2. Any program with a long waiting time due to an I/O interrupt is transferred to virtual memory. The
program returns to RAM after the I/O operation is completed. MOS handles virtual memory
management really well.
3. When using multitasking, the operating system works smoothly. All types of computer users are
pleased. A user can run a single program or numerous programs without complaints about using a
comput
4. MOS can handle multiple users running multiple apps the best. All programs run without a hiccup in
performance. All OS users are given a suitable length of time.
5. Multiple programs, such as MS Word, MS Excel, Photoshop, a browser, games, and a calculator, can
operate concurrently.

Disadvantages

1. If the computer's processor is slow, it will process programs slowly and managing many programs
will take longer. Because they require more processing power, some heavy programs cannot
operate well on a slow processor.
2. When a computer user starts many programs simultaneously, the computer slows down. Because
numerous applications are put into the main memory, the CPU is unable to provide an appropriate
time for each program and the reaction time for performing the operation increases. It is a common
problem with PCs that do not have enough RAM.
3. Multitasking keeps the processor active all the time and increases CPU heat. You need to connect
your CPU's cooling system to resolve this issue. It typically occurs when you play heavy PC games.

What is Multithreading?
Multitasking occurs when the CPU does many tasks, such as a program, process, task, or thread. Tasks are
swapped regularly so that the user can complete all of the processes at the same time. Multiple users can
share the system simultaneously. OS multitasking is accomplished by CPU scheduling and
multiprogramming.

Multiple threads are formed during multithreading. A thread in multithreading refers to a process code
section. A thread is distinguished by its program counter, thread ID, stack, and registers. If we isolate each
service into its process, each processor will share code, data, and system resources. The system may get
overloaded if we do not generate threads. Creating threads can make working with a processor easier.
Multithreading improves responsiveness, which is the most significant advantage of adopting it. The main
advantage of multithreading is resource sharing, in which multiple process threads share the same code.

Advantages and Disadvantages of Multithreading Operating System


There are various advantages and disadvantages of a multithreading OS. Some advantages and
disadvantages of a multithreading OS are as follows:

Advantages

1. In an interactive application, multithreading keeps a program running even if a section is blocked or


running time-consuming processes. It helps to improve user responsiveness.
2. Because it takes time and requires a lot of space, allocating memory and resources for process
creation is an expensive activity. Context switching and setting up threads are more cost-effective
since processes and threads share a memory. In comparison to threads, creating and managing
processes generally takes much longer.
3. A single-threaded process may only execute on a single CPU, despite the number of CPUs available.
Multithreading may run on multiple CPU machines that increase parallelism.
4. The multithreading benefits may be further enhanced in a multiprocessor system, where each
thread may run in parallel on a separate CPU. No matter how many CPUs are available, a single-
threaded operation could only operate on one of them. Multithreading improves concurrency on
multi-CPU machines.
5. Threads have little impact on the system's resources. Creating, maintaining, and managing threads
have a lower overhead than a general process.
6. The inter-process communication could be enhanced by using thread synchronization functions.
Furthermore, highly high-bandwidth, low-latency communication between multiple processes
inside an application is made possible by sharing huge volumes of data across numerous threads of
execution within the same address space.
Disadvantages

1. It requires more accurate synchronization.


2. It has the potential to devour a considerable amount of stock of blocked threads.
3. It adds overhead to context switching.
4. It requires thread or process support.
5. If the parent process requires several threads to function properly, the child processes should be
multithreaded as well.

Features Multitasking Multithreading

Definition When a single processor does many jobs (program, threads, Multitasking occurs when the CPU
process, task) at the same time, it is referred to as multitasking. a program, process, task, or thread.

Basic A CPU may perform multiple tasks at once by using the Multithreading allows a CPU to ge
multitasking method. from a job and process them all at t

Resources and The system must assign different resources and memory to The system assigns a single memor
Memory separate programs that are running concurrently in multitasking.

Switching CPU switches between programs frequently. CPU switches between the threads

Speed of It is comparatively slower in execution. It is comparatively faster in executio


Execution

Working A user may easily run several jobs off of their CPU at once. A CPU has the ability to split a sin
threads to improve its functionality

Process The process of terminating a task takes comparatively more time. It requires considerably less time to
Termination

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the
code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active state. The active
state contains two states within it: one is runnable, and the other is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the duty of the
thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each
and every thread runs for a short span of time and when that allocated time slice is over, the thread
voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice
of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their
turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally,
the most common change in the state of a thread is from runnable to running and again back to
runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the
thread is in the blocked state or is in the waiting state.

For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the
same time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread
A has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked
state is unable to perform any execution and thus never consume any cycle of the Central Processing Unit
(CPU). Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A, which is
in the waiting or blocked state.

When the main thread invokes the join() method then, it is said that the main thread is in the waiting state.
The main thread then waits for the child threads to complete their tasks. When the child threads complete
their job, a notification is sent to the main thread, which again moves the thread from waiting to the active
state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to
determine which thread to choose and which one to reject, and the chosen thread is then given the
opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered
the critical section of a code and is not willing to leave that critical section. In such a scenario, another thread
(its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is
given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real
example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method
puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution
from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and
there is no way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.

Implementation of Thread States


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

1. public static final Thread.State NEW


It represents the first state of a thread that is the NEW state.

1. public static final Thread.State RUNNABLE


It represents the runnable state.It means a thread is waiting in the queue to run.

1. public static final Thread.State BLOCKED


It represents the blocked state. In this state, the thread is waiting to acquire a lock.

1. public static final Thread.State WAITING


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

1. public static final Thread.State TIMED_WAITING


It represents the timed waiting state. The main difference between waiting and timed waiting is the time
constraint. Waiting has no time constraint, whereas timed waiting has the time constraint. A thread invoking
the following method reaches the timed waiting state.
Java Threads | How to create a thread in Java
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.

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.

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the
thread scheduler 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. Note that not
only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority


Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the
priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority
goes out of the range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


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.

Example of priority of a Thread:


FileName: ThreadPriorityExample.java

1. // Importing the required classes


2. import java.lang.*;
3.
4. public class ThreadPriorityExample extends Thread
5. {
6.
7. // Method 1
8. // Whenever the start() method is called by a thread
9. // the run() method is invoked
10. public void run()
11. {
12. // the print statement
13. System.out.println("Inside the run() method");
14. }
15.
16. // the main method
17. public static void main(String argvs[])
18. {
19. // Creating threads with the help of ThreadPriorityExample class
20. ThreadPriorityExample th1 = new ThreadPriorityExample();
21. ThreadPriorityExample th2 = new ThreadPriorityExample();
22. ThreadPriorityExample th3 = new ThreadPriorityExample();
23.
24. // We did not mention the priority of the thread.
25. // Therefore, the priorities of the thread is 5, the default value
26.
27. // 1st Thread
28. // Displaying the priority of the thread
29. // using the getPriority() method
30. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
31.
32. // 2nd Thread
33. // Display the priority of the thread
34. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
35.
36. // 3rd Thread
37. // // Display the priority of the thread
38. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
39.
40. // Setting priorities of above threads by
41. // passing integer arguments
42. th1.setPriority(6);
43. th2.setPriority(3);
44. th3.setPriority(9);
45.
46. // 6
47. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
48.
49. // 3
50. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
51.
52. // 9
53. System.out.println("Priority of the thread th3 is : " + th3.getPriority());
54.
55. // Main thread
56.
57. // Displaying name of the currently executing thread
58. System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
59.
60. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
61.
62. // Priority of the main thread is 10 now
63. Thread.currentThread().setPriority(10);
64.
65. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
66. }
67. }
Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
We know that a thread with high priority will get preference over lower priority threads when it comes to
the execution of threads. However, there can be other scenarios where two threads can have the same
priority. All of the processing, in order to look after the threads, is done by the Java thread scheduler. Refer to
the following example to comprehend what will happen if two threads have the same priority.

FileName: ThreadPriorityExample1.java

1. // importing the java.lang package


2. import java.lang.*;
3.
4. public class ThreadPriorityExample1 extends Thread
5. {
6.
7. // Method 1
8. // Whenever the start() method is called by a thread
9. // the run() method is invoked
10. public void run()
11. {
12. // the print statement
13. System.out.println("Inside the run() method");
14. }
15.
16.
17. // the main method
18. public static void main(String argvs[])
19. {
20.
21. // Now, priority of the main thread is set to 7
22. Thread.currentThread().setPriority(7);
23.
24. // the current thread is retrieved
25. // using the currentThread() method
26.
27. // displaying the main thread priority
28. // using the getPriority() method of the Thread class
29. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
30.
31. // creating a thread by creating an object of the class ThreadPriorityExample1
32. ThreadPriorityExample1 th1 = new ThreadPriorityExample1();
33.
34. // th1 thread is the child of the main thread
35. // therefore, the th1 thread also gets the priority 7
36.
37. // Displaying the priority of the current thread
38. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
39. }
40. }
Output:

Priority of the main thread is : 7


Priority of the thread th1 is : 7
Explanation: If there are two threads that have the same priority, then one can not predict which thread will
get the chance to execute first. The execution then is dependent on the thread scheduler's algorithm (First
Come First Serve, Round-Robin, etc.)

Synchronization in Java
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.
Why use Synchronization?
The synchronization is mainly used to

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

Here, we will discuss only 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. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block

3. By Using Static Synchronization

Concept of Lock in Java


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

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


implementations.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see the
example:

TestSynchronization1.java

1. class Table{
2. void printTable(int n){//method not synchronized
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.
10. }
11. }
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.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. class TestSynchronization1{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }

Java Synchronized Method


If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

TestSynchronization2.java

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.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Inter-thread Communication in Java


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
The wait() method causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

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

Method Description

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

public final void wait(long timeout)throws InterruptedException It waits for the specified amount o

2) notify() method
The 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:

1. public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()


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

Difference between wait and sleep?


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

wait() sleep()

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

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

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

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

Example of Inter Thread Communication in Java


Let's see the simple example of inter thread communication.

Test.java

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

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

You might also like