Professional Documents
Culture Documents
JPR Chapter 4
JPR Chapter 4
JPR Chapter 4
College of Engineering(Polytechnic),Pandharpur
Chapter 3
Exception Handling and Multithreading
-By
Prashant Shivaji Bhandare
Computer Engineering
SVERI’s College of Engineering(Poly), Pandharpur
Mob: 9579307314 / 7841880095
Email: psbhandare@cod.sveri.ac.in
Syllabus Mr. Bhandare P.S.
2 Hours &
Unit no & Name Content
Marks
1. What is thread? Draw thread life cycle diagram in Java. (4M) (S-17)
3
2. What is thread priority? Write default priority values and methods to change
them.(4M) (S-17)
3. What is an exception ? How it is handled ? Give suitable example. (4M) (W-16)
4. What is synchronization ? When do we use it ? Explain synchronization of two
threads. (4M) (W-16)
5. Describe life cycle of thread.(4M)(S-16) / (W-14)(S-15)(W-15) (8M)
6. Describe use of ‘throws’ with suitable example.(4M)(S-16)
7. What is thread priority ? How thread priority are set and changed ? Explain with
example (8M)(S-16)
8. Explain the following clause w.r.t. exception handling : (4M) (W-15)
(i) try (ii) catch (iii) throw (iv) finally
9. What are different types of error ? What is use of throw, throws and finally
statement ? .(8M)(W-14)
Programs Mr. Bhandare P.S.
What is exception? WAP to accept a password from the user and throw
4
“Authentication Failure” exception if the password is incorrect. (8M)(S-17)
Write a program to create two threads, one to print numbers in original order and
other in reverse order from 1 to 10. (8M) (S-17)
Write a thread program for implementing the ‘Runnable interface’. (8M)(W-16)
Define an exception called ‘No match Exception’ that is thrown when a string is
not equal to “MSBTE”. Write program. (8M) (W-16)
Write a program to input name and age of person and throws user defined
exception, if entered age is negative .(8M) (S-16) (S-15)
Write a program to accept password from user and throw ‘Authentication failure’
exception if password is incorrect.(8M)(W-15)
Write a program to create two threads ; one to print numbers in original order and
other to reverse order from 1 to 50.(8M) (W-14)
Mr. Bhandare P.S.
5
About Title of Chapter
Also Student are going to learn what are the different method used
for exception handling.
Mr. Bhandare P.S.
The central idea of the chapter is that the new concept i.e exception
handling & how multithreading is done in java
Also what are the packages needed for exception & multithreading
concept.
Mr. Bhandare P.S.
7 Importance of Chapter
8
Objectives of chapter
By studying this chapter student will able to learn.
1. To handle the exceptions in programs effectively.
2. They will also learn ‘how to make their programs multithreaded’, set thread
priorities, and the concept of deadlock.
3. How write our own exception & use it program.
4. What are the different steps of thread life cycle.
5. What are the different statements & are how they are used to handle exception
Exception Handling : Introduction Mr. Bhandare P.S.
10
A Java exception is an object that describes an exceptional (that is,
error) condition that has occurred in a piece of code.
That method may choose to handle the exception itself, or pass it on.
Briefly, here is how they work. Program statements that you want to
monitor for exceptions are contained within a try block.
Your code can catch this exception (using catch) and handle it in
some rational manner.
13
To manually throw an exception, use the keyword throw.
try {
14 // block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.
Exception Types Mr. Bhandare P.S.
17
Exceptions of type Error are used by the Java run-time system to
indicate errors having to do with the run-time environment, itself.
19
Exception Mr. Bhandare P.S.
When the Java run-time system detects the attempt to divide by zero, it
24
constructs a new exception object and then throws this exception.
This causes the execution of Exc0 to stop, because once an exception has
been thrown, it must be caught by an exception handler and dealt with
immediately.
The resulting stack trace from the default exception handler shows how
27
the entire call stack is displayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
As you can see, the bottom of the stack is main’s line 7, which is the
call to subroutine( ), which caused the exception at line 4.
The call stack is quite useful for debugging, because it pinpoints the
precise sequence of steps that led to the error.
Exception handling using try and catch Mr. Bhandare P.S.
In order to take these two benefits Java has provided the mechanism of
try-catch blocks.
try Mr. Bhandare P.S.
{
29
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
//.......
Mr. Bhandare P.S.
Here, ExceptionType is the type of exception that has occurred and exOb.
30
The keyword try is used to preface a block of code that is likely to cause an
error condition and throw an exception.
The catch block catches the exception thrown by the try block and handles
it appropriately.
31
// an example of simple try-catch Mr. Bhandare P.S.
class ArException {
32
public static void main(String args[]) {
int x = 56;
int y = 0;
try {
int z = x/y; //statement1
System.out.println("Value: "+z);
}
catch(ArithmeticException e) {
System.out.println("DIVISION BY ZERO");
}
System.out.println("End of program...");
}
}
Mr. Bhandare P.S.
That’s why, the statement after statement1 will not be executed. The
control will directly get transferred to catch statement.
Program will not terminate here. Last statement of the program is also
getting executed.
A try and its catch statement form a unit. Mr. Bhandare P.S.
You cannot use try on a single statement. Remember, the variables declared
inside the try block are having local scope or block scope for the particular
block.
Displaying a Description of an Exception Mr. Bhandare P.S.
2. void printStackTrace()
It prints the stack trace on the standard error stream.
The stack trace comprises the method invocation sequence on the runtime
stack when the exception was thrown.
It gives the same output as when exception is occurred but here the
program is not terminated.
Mr. Bhandare P.S.
3. String toString()
36
Instead of these methods directly the object can also be referred to print the
description of the exception.
class ExMethods {
37
public static void main(String args[]) { System.out.println("\ntoString:-");
int x = 56; System.out.println(e.toString());
int y = 0; System.out.println("\nReferring object:-");
try { System.out.println(e);
int z = x/y; }
System.out.println("Value: "+z); System.out.println("\nEnd of program...");
} }
catch(ArithmeticException e) }
{
System.out.println("getMessage:-");
System.out.println(e.getMessage());
System.out.println("\nprintStackTrace:-");
Output: Mr. Bhandare P.S.
getMessage:-
38
/ by zero
printStackTrace:-
java.lang.ArithmeticException: / by zero
at ExMethods.main(ExMethods.java:10)
toString:-
java.lang.ArithmeticException: / by zero
Referring object:-
java.lang.ArithmeticException: / by zero
End of program...
Multiple catch Clauses Mr. Bhandare P.S.
39 In some cases, more than one exception could be raised by a single piece
of code.
To handle this type of situation, you can specify two or more catch clauses,
each catching a different type of exception.
After one catch statement executes, the others are bypassed, and execution
continues after the try / catch block.
42 C:\>java MultipleCatches
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
If you try to compile this program, you will receive an error message stating
45
that the second catch statement is unreachable because the exception has
already been caught.
This means that the second catch statement will never execute.
The try statement can be nested. That is, a try statement can be inside the block
46 of another try.
Each time a try statement is entered, the context of that exception is pushed on
the stack.
If an inner try statement does not have a catch handler for a particular exception,
the stack is unwound and the next try statement’s catch handlers are inspected
for a match.
This continues until one of the catch statements succeeds, or until all of the
nested try statements are exhausted.
If no catch statement matches, then the Java run-time system will handle the
exception.
Mr. Bhandare P.S.
import java.util.Scanner; System.out.println("Inner try end...");
47 class NestTry { }
public static void main(String args[]) { catch(ArrayIndexOutOfBoundsException e)
int x,z; //1 {
try { }
catch(ArithmeticException e) //2 {
z = 82 / x; //statement1
System.out.println("Division: "+z); System.out.println("Division by zero");
try { }
System.out.println("Program end...");
int a = 100 / (x-1); //statement2
short arr[] = {15}; }
Program has nested two try statements in each other. We have taken input as
48 a number from keyboard and stored in into variable x.
When value of x inputted is 1. The outer try will work properly. In inner try,
the statement2 will cause the exception of “Divide by zero”.
In this case, the program control will get directly transferred to inner try’s
catch block i.e. catch clause no. 1. But the exception object will not match.
Mr. Bhandare P.S.
So it will check for outer try’s catch clause. Now, the match is found.
49
That’s why, we got the output no.2.
In the third case, when the input is any number other than 0 and 1,
statement3 will cause an exception “Array index out of bounds”.
50 import java.util.Scanner;
class NestTryMethod {
public static void myMeth() {
try {
int arr[] = new int[-2]; //statement1
arr[4] = 10;
}
catch(ArithmeticException e) //1 {
System.out.println("Exception:"+e);
}
}
public static void main(String args[]) catch(ArithmeticException e) //3
Mr. Bhandare P.S.
int a,b; {
51
Scanner in = new Scanner(System.in); System.out.println("Exception:"+e);
System.out.print("Enter the number : "); }
a = in.nextInt(); System.out.println("Program end...");
try { }
b = 40 / a; //statement2 }
System.out.println("Division: "+b);
NestTryMethod.myMeth(); //statement3
}
catch(NegativeArraySizeException e) //2
{
System.out.println("Exception:"+e);
}
Mr. Bhandare P.S.
The program control will get returned and it will transfer to catch clause 2.
Now the match will found. So the action will be taken.
throw Mr. Bhandare P.S.
you have only been catching exceptions that are thrown by the Java run-
53 time system.
There are two ways you can obtain a Throwable object: using a parameter
54
in a catch clause or creating one with the new operator.
The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed.
55
If not, then the next enclosing try statement is inspected, and so on.
This program gets two chances to deal with the same error. First, main( )
57
sets up an exception context and then calls demoproc( ).
When the second form is used, the argument specifies a string that
describes the exception. This string is displayed when the object is used as
an argument to print( ) or println( ).
All other exceptions that a method can throw must be declared in the
throws clause. If they are not, a compile-time error will result.
Mr. Bhandare P.S.
class ThrowsDemo {
62
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
Above example is an example of an incorrect program that tries to throw an
exception that it does not catch.
Because the program does not specify a throws clause to declare this fact, the
program will not compile.
Mr. Bhandare P.S.
class M{
65
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Mr. Bhandare P.S.
4) Throw is used within the method. Throws is used with the method signature.
67 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.
69
For example, if a method opens a file upon entry and closes it upon exit,
then you will not want the code that closes the file to be bypassed by the
exception-handling mechanism.
finally creates a block of code that will be executed after a try /catch block
72 has completed and before the code following the try/catch block.
Any time a method is about to return to the caller from inside a try/catch
block, via an uncaught exception or an explicit return statement, the
finally clause is also executed just before the method returns.
Mr. Bhandare P.S.
This can be useful for closing file handles and freeing up any other
73
resources that might have been allocated at the beginning of a method
with the intent of disposing of them before returning.
75
try
{
.......
}
finally
{
.......
}
Mr. Bhandare P.S.
In this example, procA( ) prematurely breaks out of the try by throwing an exception.
78
The finally clause is executed on the way out. procB( )’s try statement is exited via a
return statement.
The finally clause is executed before procB( ) returns. In procC( ), the try statement
executes normally, without error.
79
Final is used to apply restrictions Finally is used to place important code, Finalize is used to
on class, method and variable. it will be executed whether exception perform clean up
is handled or not. processing just before
1) Final class can't be inherited, final object is garbage
method can't be overridden and collected.
final variable value can't be
changed.
class FinalExample
{
public static void main(String[] args)
{
final int x=100;
x=200;// Compile Time Error
}
}
Java finally example Mr. Bhandare P.S.
class FinallyExample
81
{
public static void main(String[] args)
{
try{
int x=300;
}
catch(Exception e)
{
System.out.println(e);
}
Finally
{
System.out.println("finally block is executed");
}
}
}
Java finalize example Mr. Bhandare P.S.
82 class FinalizeExample {
public void finalize() {
System.out.println("finalize called");
}
public static void main(String[] args) {
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}
}
Java’s Built-in Exceptions Mr. Bhandare P.S.
The most general of these exceptions are subclasses of the standard type
RuntimeException.
86
(Java Custom Exception )
Although Java’s built-in exceptions handle most common errors, you will
probably want to create your own exception types to handle situations specific
to your applications.
This is quite easy to do: just define a subclass of Exception (which is, of
course, a subclass of Throwable).
The Exception class does not define any methods of its own. It does, of
course, inherit those methods provided by Throwable.
Mr. Bhandare P.S.
Thus, all exceptions, including those that you create, have the methods
87 defined by Throwable available to them.
The first form creates an exception that has no description. The second
form lets you specify a description of the exception.
Mr. Bhandare P.S.
By overriding toString( ), you can prevent the exception name and colon
from being displayed.
Java has defined a lot of Exception and Error classes for different
89
conditions.
The Exception class does not define any methods of its own.
90
Thus, all exceptions, including those that we create, have the methods
defined by Throwable available to them.
In order to create our own exception we need to derive our class from
Exception.
Mr. Bhandare P.S.
{ System.out.println("Caught: "+e);
92
public static void main(String args[]) }
{ }
int x = Integer.parseInt(args[0]); }
int y = Integer.parseInt(args[1]);;
int z;
try
{
z = x * y;
if(z<0) //statement1
throw new NegativeOutputException(z);
System.out.println("Output: "+z);
}
catch (NegativeOutputException e)
Mr. Bhandare P.S.
Observe the program. In order to create our own exception we have
93 inherited our exception class from java.lang.Exception.
The condition for the exception defined is that when the result of the
expression is negative then exception must occur.
It is defined in statement1. The input has taken from the command line.
First argument is passed to x and second to y.
Mr. Bhandare P.S.
First time and third time when both the arguments are positive/negative the
94
result is positive so we will get the output properly.
But when any one of the arguments is negative the result is also negative.
The statement1 will be true.
If we do not catch it using catch the compile time error will occur.
Chained Exceptions Mr. Bhandare P.S.
Beginning with JDK 1.4, a feature was incorporated into the exception
95
subsystem: chained exceptions.
However, the actual cause of the problem was that an I/O error occurred,
which caused the divisor to be set improperly.
Mr. Bhandare P.S.
Chained exceptions let you handle this, and any other situation in which
layers of exceptions exist.
In the first form, causeExc is the exception that causes the current
97
exception.
The second form allows you to specify a description at the same time
that you specify a cause exception.
These two constructors have also been added to the Error, Exception,
and RuntimeException classes.
Mr. Bhandare P.S.
The chained exception methods supported by Throwable are getCause()
98 and initCause().
Throwable getCause( )
Throwable initCause(Throwable causeExc)
The getCause( ) method returns the exception that underlies the current
exception.
Thus, you can associate a cause with an exception after the exception has
been created. However, the cause exception can be set only once
Mr. Bhandare P.S.
// Demonstrate exception chaining.
99 class ChainExcDemo
{
static void demoproc()
{
// create an exception
NullPointerException e =
new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[]) { Mr. Bhandare P.S.
100 try {
demoproc();
} catch(NullPointerException e) {
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +
e.getCause());
}
}
}
Three Recently Added Exception Features Mr. Bhandare P.S.
101 Beginning with JDK 7, three interesting and useful features have been
added to the exception system.
It is not uncommon for two or more exception handlers to use the same
code sequence even though they respond to different exceptions.
Instead of having to catch each exception type individually, you can use a
single catch clause to handle all of the exceptions without code duplication.
To use a multi-catch, separate each exception type in the catch clause with
the OR operator.
// Demonstrate the multi-catch feature. Mr. Bhandare P.S.
class MultiCatch {
103
public static void main(String args[]) {
int a=10, b=0;
int vals[] = { 1, 2, 3 };
try {
int result = a / b; // generate an ArithmeticException
// vals[10] = 19; // generate an ArrayIndexOutOfBoundsException
// This catch clause catches both exceptions.
} catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
System.out.println("After multi-catch.");
}
}
Using Exceptions Mr. Bhandare P.S.
Unlike some other languages in which error return codes are used to
indicate failure, Java uses exceptions.
105
This is a cleaner way to handle failure modes.
If you do so, it will only confuse your code and make it hard to
maintain.
Multithreaded Programming Mr. Bhandare P.S.
Each part of such a program is called a thread, and each thread defines a
separate path of execution.
This means that a single program can perform two or more tasks
simultaneously.
For instance, a text editor can format text at the same time that it is printing,
as long as these two actions are being performed by two separate threads.
Thus, process-based multitasking deals with the “big picture,” and thread-
based multitasking handles the details.
Mr. Bhandare P.S.
Processes are heavyweight tasks that require their own separate address
spaces.
Threads are lightweight. They share the same address space and
cooperatively share the same heavyweight process.
Once initiated by main thread they can run concurrently and share the
resources jointly.
Threads running in parallel do not actually mean that they are running at
the same time.
Since, all threads are running on the single processor, the flow of execution
is shared among the threads.
Mr. Bhandare P.S.
The Java run-time system depends on threads for many things, and all
114
the class libraries are designed with multithreading in mind.
Once this polling mechanism returns with, say, a signal that a network file
is ready to be read, then the event loop dispatches control to the
appropriate event handler.
Until this event handler returns, nothing else can happen in the program.
This wastes CPU time. It can also result in one part of a program
dominating the system and preventing any other events from being
processed.
Mr. Bhandare P.S.
One thread can pause without stopping other parts of your program.
For example, the idle time created when a thread reads data from a
network or waits for user input can be utilized elsewhere.
Mr. Bhandare P.S.
When a thread blocks in a Java program, only the single thread that is
blocked pauses. All other threads continue to run.
As most readers know, over the past few years, multi-core systems have
become commonplace.
It can be ready to run as soon as it gets CPU time. A running thread can be
119
suspended, which temporarily halts its activity.
120
Mr. Bhandare P.S.
There are many threads in which a thread can enter during its life-time.
121
These are:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
It can be shifted from one state to another via variety of ways as shown in
figure.
Newborn state Mr. Bhandare P.S.
122 After creation of the thread object, the thread is born which is called as
newborn thread. This thread is not scheduled for running.
We can either start this state to make it runnable using start( ) method or
kill the thread using stop( ) method.
Only these two operations can be performed on this state of the thread.
When the thread is ready for execution and is waiting for availability of the
123 processor, it is said to be in runnable state.
The thread has joined the queue of threads that are waiting for execution.
If all the threads have equal priority, then they are given time slots for
execution in round robin fashion i.e. on first come first serve basis.
The thread that relinquishes control joins the queue at the end and again
waits for its execution.
124 When the processor has given time to the thread for its execution then the
thread is said to be in running state.
A running thread may relinquish its control in any one of the following
situations:
Mr. Bhandare P.S.
1. The thread has been suspended using suspend( ) method. This canbe
125
revived by using resume( ) method. This is useful when we want to
suspend a thread for some time rather than killing it.
2. We can put a thread to sleep using sleep (time) method where ‘time’ is
the time value given in milliseconds. Means, the thread is out of queue
during this time period.
3. A thread can wait until some event occurs using wait( ) method. This
thread can be scheduled to run again using notify( ) method.
Blocked state Mr. Bhandare P.S.
126
When a thread is prevented from entering into the runnable state and
subsequently in running state it is said to be blocked.
A blocked thread is considered “not runnable” but not dead and therefore
fully qualified to run again.
Mr. Bhandare P.S.
Dead state
127
A running thread ends its life when it has completed its execution of
run() method.
It is a natural death.
However we can kill it by sending the stop message to it at any state thus
causing a premature death to it.
128 Java’s multithreading system is built upon the Thread class, its methods,
and its companion interface called Runnable.
The Thread class defines several methods that help manage threads.
Mr. Bhandare P.S.
129
Method Meaning
When a Java program starts up, one thread begins running immediately.
130
This is usually called the main thread of your program, because it is the one
that is executed when your program begins.
Once you have a reference to the main thread, you can control it just like
any other thread.
Let’s begin by reviewing the following example: Mr. Bhandare P.S.
In this program, a reference to the current thread (the main thread, in this
133 case) is obtained by calling currentThread( ), and this reference is stored in
the local variable t.
The program then calls setName( ) to change the internal name of the
thread.
Next, a loop counts down from five, pausing one second between each
line.
Mr. Bhandare P.S.
The sleep( ) method causes the thread from which it is called to suspend
execution for the specified period of milliseconds.
As the preceding program shows, you can set the name of a thread by
136 using setName( ).
These methods are members of the Thread class and are declared like this:
final void setName(String threadName)
final String getName( )
137 In the most general sense, you create a thread by instantiating an object of
type Thread.
The easiest way to create a thread is to create a class that implements the
138
Runnable interface.
It is important to understand that run( ) can call other methods, use other
139
classes, and declare variables, just like the main thread can.
The only difference is that run( ) establishes the entry point for another,
concurrent thread of execution within your program.
After you create a class that implements Runnable, you will instantiate an
object of type Thread from within that class.
Mr. Bhandare P.S.
Thread defines several constructors. The one that we will use is shown here:
140
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the
Runnable interface.
This defines where execution of the thread will begin. The name of the new
thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( )
method, which is declared within Thread.
In essence, start( ) executes a call to run( ). The start( ) method is shown here:
void start( )
Mr. Bhandare P.S.
143 The second way to create a thread is to create a new class that extends
Thread, and then to create an instance of that class.
The extending class must override the run( ) method, which is the entry
point for the new thread.
class MultiThreadDemo {
147
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Using isAlive( ) and join( ) Mr. Bhandare P.S.
148 As mentioned, often you will want the main thread to finish last.
First, you can call isAlive( ) on the thread. This method is defined by
Thread, and its general form is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is
still running. It returns false otherwise.
While isAlive( ) is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join( ), shown here:
Its name comes from the concept of the calling thread waiting until the
specified thread joins it.
name = threadname; }
System.out.println(name + " exiting.");
t = new Thread(this, name);
System.out.println("New thread: " + t); }
t.start(); }
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
class DemoJoin { ob3.t.join(); Mr. Bhandare P.S.
Thread priorities are used by the thread scheduler to decide when each
153
thread should be allowed to run.
In practice, the amount of CPU time that a thread gets often depends on
several factors besides its priority.
Here, level specifies the new priority setting for the calling thread.
155
To return a thread to default priority, specify NORM_PRIORITY, which is
currently 5.
You can obtain the current priority setting by calling the getPriority( )
method of Thread, shown here:
final int getPriority( )
class ThreadPrio
157
{
public static void main(String args[]) throws InterruptedException
{
Thread.currentThread().setPriority(10); // statement1
NewThread abc = new NewThread(7,"ABC"); // statement2
NewThread xyz = new NewThread(3,"XYZ"); // statement3
abc.start(); // statement4
xyz.start(); // statement5
Thread.sleep(1000); //statement6
System.out.println("Main thread exiting.");
}
}
Mr. Bhandare P.S.
The statement2 and statement3 creates the thread named “ABC” and
“XYZ” with priorities 7 and 3 respectively.
Observe the snapshot of the output, the highest priority thread is executed
more number of times than the lower priority one.
Mr. Bhandare P.S.
That is, it depends upon the algorithm that the operating system uses for
thread scheduling.
Thread synchronization Mr. Bhandare P.S.
160 When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a
time.
As you will see, Java provides unique, language-level support for it.
All other threads attempting to enter the locked monitor will be suspended
until the first thread exits the monitor.
A thread that owns a monitor can reenter the same monitor if it so desires
Mr. Bhandare P.S.
This means that the lock from any Java object can be used to implement
mutual exclusion.
By associating a shared resource with a Java object and its lock, the object
can act as a guard, ensuring synchronized access to the resource.
At a time, only one thread can access the shared resource guarded by the
object lock.
Mr. Bhandare P.S.
1. A thread must acquire the object lock associated with a shared resource,
before it can enter the shared resource.
The runtime system ensures that no other thread can enter a shared
resource if another thread already holds the object lock associated with
the shared resource.
2. When a thread exits a shared resource, the runtime system ensures that
164 the object lock is also handed over.
If another thread is waiting for this object lock, it can proceed to acquire
the lock in order to access to the shared resource.
The keyword ‘synchronized’ and the lock forms the basis for
implementing synchronized execution of code.
165 As all objects have their own implicit monitor associated with them,
synchronization is easy in Java.
In order to enter an object’s lock, we just need to call a method that has
been modified with the keyword ‘synchronized’.
To exit the lock and give up control of the object to the next waiting
thread, the owner of that lock simply returns from the synchronized
method.
Mr. Bhandare P.S.
168
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Mr. Bhandare P.S.
Output:
5
169
100
10
200
15
300
20
400
25
500
Mr. Bhandare P.S.
Observe the output, by calling sleep( ), the call( ) method allows execution
170
to switch to another thread.
In above program, nothing exists to stop all three threads from calling the
same method, on the same object, at the same time.
This is known as a race condition, because the three threads are racing
each other to complete the method display( ).
This example used sleep( ) to make the effects repeatable and obvious.
Mr. Bhandare P.S.
Many times, a race condition is more subtle and less predictable, because we
171 can’t be sure when the context switch will occur.
This can cause a program to run right one time and wrong the next time.
So, we must serialize access to display( ) method. That is, we must have to
restrict its access to only one thread at a time.
For this, we simply need to precede display( ) method’s definition with the
keyword ‘synchronized’, such as:
class JavaProg {
synchronized void display(String name,int num) {
………….
………….
}
}
Synchronized blocks Mr. Bhandare P.S.
If we want to synchronize the current object and its methods then the
‘this’ keyword can be used instead of ‘object’.
Output:
177
5
100
10
200
15
300
20
400
25
500
Mr. Bhandare P.S.
synchronized (classname.class)
{
//code block to be synchronized
}
The block synchronizes on the lock of the object denoted by the reference
classname.class.
Mr. Bhandare P.S.
All three methods can be called only from within a synchronized context.
The threads execute wait( ) and notify( ) (or notifyAll( )) methods on the
182
shared object for this purpose.
These final methods are defined in the Object class, and therefore, inherited
by all objects.
These methods are used to avoid the polling. Polling is usually implemented
by a loop that is used to check some condition repeatedly.
This wastes some CPU time. For example, consider the producer-
183
consumer problem, where one thread is producing some data and another
is consuming it.
Here, the producer has to wait until the consumer is finished before it
generates more data.
In a polling system, the consumer would waste many CPU cycles while it
waited for the producer to produce.
Once the producer was finished, it would start polling, wasting more CPU
cycles waiting for the consumer to finish, and so on.
Mr. Bhandare P.S.
wait( ): It is used to tell the calling thread to give up the lock and go to
185
sleep until some other thread enters the same lock and calls notify( ).
notify( ): It wakes up the first thread that called wait( ) on the same
object.
notifyAll( ): It wakes up all the threads that called wait( ) on the same
object.
Additional forms of wait( ) exist that allow you to specify a period of time
to wait.
1) wait() method Mr. Bhandare P.S.
Causes current thread to release the lock and wait until either another thread invokes the
187 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.
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()
Mr. Bhandare P.S.
Output:
192
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
Mr. Bhandare P.S.
This causes its execution to suspend until the Producer notifies you that
some data is ready.
This tells Producer that it is now okay to put more data in the queue.
When execution resumes, the next item of data is put in the queue, and
194
notify( ) is called.
Here the variable ‘isSet’ plays an important role to check whether the
consume( ) or produce( ) has finished their task properly.
197
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
198 A special type of error that you need to avoid that relates
specifically to multitasking is deadlock, which occurs when
two threads have a circular dependency on a pair of
synchronized objects.
In general, it occurs only rarely, when the two threads time-slice in just the
right way.
It may involve more than two threads and two synchronized objects.
Mr. Bhandare P.S.
The next example creates two classes, A and B, with methods foo( ) and
bar( ), respectively, which pause briefly before trying to call a method in
the other class.
The main class, named Deadlock, creates an A and a B instance, and then
starts a second thread to set up the deadlock condition.
The foo( ) and bar( ) methods use sleep( ) as a way to force the deadlock
condition to occur.
Mr. Bhandare P.S.
class B { a.last();
202
synchronized void bar(A a) { }
String name =
Thread.currentThread().getName(); synchronized void last() {
System.out.println(name + " entered System.out.println("Inside A.last");
B.bar");
}
}
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call
A.last()");
Mr. Bhandare P.S.
205
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test Mr. Bhandare P.S.
206 {
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}
}
Deadlock in java Mr. Bhandare P.S.
207
Deadlock in java is a part of multithreading. Deadlock can occur in a
situation when a thread is waiting for an object lock, that is acquired by
another thread and second thread is waiting for an object lock that is
acquired by first thread.
Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.
public class TestDeadlockExample1 { Mr. Bhandare P.S.
If you make any static method as synchronized, the lock will be on the class not
210 on object.
•class Table{
•synchronized static void printTable(int n)
•{
• for(int i=1;i<=10;i++)
•{
• System.out.println(n*i);
• try
•{
• Thread.sleep(400);
• }catch(Exception e){}
• }
•}
•}
Mr. Bhandare P.S.
211
class MyThread1 extends Thread{
public void run(){ class MyThread3 extends Thread{
Table.printTable(1); public void run(){
} Table.printTable(100);
} }
}
213
214
1. What is an exception ? How it is handled ? Give suitable example.
(4M)
215
3. What is thread priority ? How thread priority are set and changed ? Explain
with example.(8M)
4. Write a program to input name and age of person and throws user defined
exception, if entered age is negative .(8M)
Winter 2015 Mr. Bhandare P.S.
216
1. What is exception ? How it is handled ? Explain with suitable example.
(4M)
2. Explain the following clause w.r.t. exception handling : (4M)
(i) try
(ii) catch
(iii) throw
(iv) finally
217
2. Explain thread priority and method to get and set priority values. (4M)
3. Write a program to input name and age of a person and throws an user define
exception if entered age is negative(8M)
4. With suitable diagram explain life cycle of Thread. (8M)
Winter 2014 Mr. Bhandare P.S.
218
1. Explain following methods related to threads :
1) suspend ( ) 2) resume ( ) 3) yield ( ) 4) wait ( ). (4M)
3. Write a program to create two threads ; one to print numbers in original order and
other to reverse order from 1 to 50.(8M)
4. What are different types of error ? What is use of throw, throws and finally
statement ? .(8M)