JPR Chapter 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 218

SVERI’s

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

4.1 Errors and Exception :Types of errors,


exceptions, try and catch statement, nested try
statement, throws and Finally statement, build-in
exceptions, chained exceptions, creating own
exception(throw clause), subclasses.
Unit IV -
Exception Handling 08 Hrs.
and Multithreading
4.2 Multithreaded Programming Creating a Thread:
12 Mks.
By extending to thread class and by implementing
runnable Interface, Life cycle of thread: Thread
Methods: wait, sleeps, notify , resumes, suspend(),
stop().Thread exceptions. thread priority and
methods, synchronization, inter-thread
communication. deadlock.
Assignment no. 4 Mr. Bhandare P.S.

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

The title of chapter “Exception Handling & Multithreaded


Programming ” gives idea that in this chapter students are going to
learns one of the most important feature of java i.e. Exception
Handling & Multithreaded Programming.

Also Student are going to learn what are the different method used
for exception handling.
Mr. Bhandare P.S.

6 About Central Idea of Chapter

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

This chapter is important because it gives introduction to concept in


java which is widely used in current life problems.

Also this chapter is important as it includes creating threads & using


them for creating multithreaded program.
Mr. Bhandare P.S.

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.

9  An exception is an abnormal condition that arises in a code sequence at


run time.

 In other words, an exception is a run-time error.

 In computer languages that do not support exception handling, errors


must be checked and handled manually—typically through the use of error
codes, and so on.

 This approach is as cumbersome as it is troublesome.

 Java’s exception handling avoids these problems and, in the process,


brings run-time error management into the object-oriented world.
Exception-Handling Fundamentals 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.

When an exceptional condition arises, an object representing that


exception is created and thrown in the method that caused the error.

That method may choose to handle the exception itself, or pass it on.

Either way, at some point, the exception is caught and processed.


Mr. Bhandare P.S.

Exceptions can be generated by the Java run-time system, or they


11
can be manually generated by your code.

Exceptions thrown by Java relate to fundamental errors that violate


the rules of the Java language or the constraints of the Java
execution environment.

Manually generated exceptions are typically used to report some


error condition to the caller of a method.
Mr. Bhandare P.S.

Java exception handling is managed via five keywords: try, catch,


12 throw, throws, and finally.

 Briefly, here is how they work. Program statements that you want to
monitor for exceptions are contained within a try block.

If an exception occurs within the try block, it is thrown.

Your code can catch this exception (using catch) and handle it in
some rational manner.

System-generated exceptions are automatically thrown by the Java


run-time system.
Mr. Bhandare P.S.

13
To manually throw an exception, use the keyword throw.

Any exception that is thrown out of a method must be specified as


such by a throws clause.

Any code that absolutely must be executed after a try block


completes is put in a finally block.
 This is the general form of an exception-handling block: Mr. Bhandare P.S.

 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.

15 All exception types are subclasses of the built-in class Throwable.

 Thus, Throwable is at the top of the exception class hierarchy.

 Immediately below Throwable are two subclasses that partition


exceptions into two distinct branches.

 One branch is headed by Exception.

This class is used for exceptional conditions that user programs


should catch.
Mr. Bhandare P.S.

There is an important subclass of Exception, called


16
RuntimeException.

Exceptions of this type are automatically defined for the programs


that you write and include things such as division by zero and invalid
array indexing.

The other branch is topped by Error, which defines exceptions that


are not expected to be caught under normal circumstances by your
program.
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.

 Stack overflow is an example of such an error.

 This chapter will not be dealing with exceptions of type Error,


because these are typically created in response to catastrophic
failures that cannot usually be handled by your program.
Mr. Bhandare P.S.

18 The top-level exception hierarchy is shown here


Mr. Bhandare P.S.

19
Exception Mr. Bhandare P.S.

 The class Exception represents exceptions that a program would want to


20
be made aware of during execution.

 Its subclass RuntimeException represents many common programming


errors that manifest at runtime.

 Other subclasses of the Exception class define other categories of


exceptions, for example, I/O-related exceptions (IOException,
FileNotFoundException, EOFException) and GUI-related exceptions
(AWTException).

 Remember here IOException is subclass of Exception which is defined in


package java.io.
RuntimeException Mr. Bhandare P.S.

21  Runtime exceptions, like out-of-bound array indices


(ArrayIndexOutOfBounds Exception), uninitialized references
(NullPointerException), illegal casting of references
(ClassCastException), illegal parameters (IllegalArgumentException),
division by zero (ArithmeticException) and number format problems
(NumberFormatException) are all subclasses of the java.lang.

 RuntimeException class, which is a subclass of the Exception class.

 As these runtime exceptions are usually caused by program bugs that


should not occur in the first place.
Error Mr. Bhandare P.S.

22  The subclass AssertionError of the java.lang.Error class is used by


the Java assertion facility.

 Other subclasses of the java.lang.Error class define exceptions that


indicate class linkage (LinkageError), thread (ThreadDeath), and
virtual machine (VirtualMachineError) related problems.

 These are invariably never explicitly caught and are usually


irrecoverable.
Uncaught Exceptions Mr. Bhandare P.S.

23  Before you learn how to handle exceptions in your program, it is useful


to see what happens when you don’t handle them.

 This small program includes an expression that intentionally causes a


divide-by-zero error:
class Exc0 {
 public static void main(String args[]) {
 int d = 0;
 int a = 42 / d;
 }
}
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.

 In this example, we haven’t supplied any exception handlers of our own,


so the exception is caught by the default handler provided by the Java
run-time system.

 Any exception that is not caught by your program will ultimately be


processed by the default handler.
Mr. Bhandare P.S.

 The default handler displays a string describing the exception, prints a


25 stack trace from the point at which the exception occurred, and terminates
the program.
 Here is the exception generated when this example is executed:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
 Notice how the class name, Exc0; the method name, main; the filename,
Exc0.java; and the line number, 4, are all included in the simple stack
trace.

 Also, notice that the type of exception thrown is a subclass of Exception


called ArithmeticException, which more specifically describes what type
of error happened.
Mr. Bhandare P.S.
 The stack trace will always show the sequence of method invocations
26 that led up to the error.
 For example, here is another version of the preceding program that
introduces the same error but in a method separate from main( ):
 class Exc1 {
 static void subroutine() {
 int d = 0;
 int a = 10 / d;
 }
 public static void main(String args[]) {
 Exc1.subroutine();
 }
}
Mr. Bhandare P.S.

 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.

28  The default exception handler provided by the Java run-time system is


useful for debugging; we will usually want to handle an exception by
ourselves.

 It provides two benefits. First, it allows us to fix the errors. Second, it


prevents the program from automatically terminating.

 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.

 The catch block is added immediately after the try block.

 Fig. shows this exception handling mechanism.


Mr. Bhandare P.S.

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.

 Observe the program; here in the statement1 an attempt of divide by zero


33 is made.

 So it creates an exception object of type ArithmeticException and throws


out of it.

 That’s why, the statement after statement1 will not be executed. The
control will directly get transferred to catch statement.

 Thus line “DIVISION BY ZERO” is printed on the output.

 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.

34  The scope of the catch clause is restricted to those statements specified by


the immediately after try statement.

 A catch statement cannot catch an exception thrown by another try


statement (except in the case of nested try statements, described next).

 The statements that are protected by try must be surrounded by curly


braces. (That is, they must be within a block.)

 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.

35  The class Throwable provides following common methods to query the


exception. So they can be used along with the Exception class’ object.
1. String getMessage()
 It returns the detail message of the exception.

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

 It returns a short description of the exception, which typically comprises


the class name of the exception together with the string returned by the
getMessage() method.

 Instead of these methods directly the object can also be referred to print the
description of the exception.

 The program illustrates the use of all these methods.


 // Description of exception  e.printStackTrace(); Mr. Bhandare P.S.

 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.

 When an exception is thrown, each catch statement is inspected in order,


and the first one whose type matches that of the exception is executed.

 After one catch statement executes, the others are bypassed, and execution
continues after the try / catch block.

 The following example traps two different exception types:


 // Demonstrate multiple catch statements.
Mr. Bhandare P.S.
 class MultipleCatches {
40  public static void main(String args[]) {
 try {
 int a = args.length;
 System.out.println("a = " + a);
 int b = 42 / a;
 int c[] = { 1 };
 c[42] = 99;
 } catch(ArithmeticException e) {
 System.out.println("Divide by 0: " + e);
 } catch(ArrayIndexOutOfBoundsException e) {
 System.out.println("Array index oob: " + e);
 }
 System.out.println("After try/catch blocks.");
 }
 }
Mr. Bhandare P.S.

 This program will cause a division-by-zero exception if it is started with no


41 command-line arguments, since a will equal zero.

 It will survive the division if you provide a command-line argument,


setting a to something larger than zero.

 But it will cause an ArrayIndexOutOfBoundsException, since the int


array c has a length of 1, yet the program attempts to assign a value to
c[42].

 Here is the output generated by running it both ways


Mr. Bhandare P.S.

42  C:\>java MultipleCatches
 a=0
 Divide by 0: java.lang.ArithmeticException: / by zero
 After try/catch blocks.

 C:\>java MultipleCatches TestArg


 a=1
 Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
 After try/catch blocks.
Mr. Bhandare P.S.
 When you use multiple catch statements, it is important to remember that
43 exception subclasses must come before any of their superclasses.

 This is because a catch statement that uses a superclass will catch


exceptions of that type plus any of its subclasses.

 Thus, a subclass would never be reached if it came after its superclass.

 Further, in Java, unreachable code is an error.

 For example, consider the following program:


 class SuperSubCatch { Mr. Bhandare P.S.

 public static void main(String args[]) {


44
 try {
 int a = 0;
 int b = 42 / a;
 } catch(Exception e) {
 System.out.println("Generic Exception catch.");
 }
 /* This catch is never reached because
 ArithmeticException is a subclass of Exception. */
 catch(ArithmeticException e) { // ERROR – unreachable
 System.out.println("This is never reached.");
 }
 }
}
Mr. Bhandare P.S.

 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.

 Since ArithmeticException is a subclass of Exception, the first catch


statement will handle all Exception-based errors, including
ArithmeticException.

 This means that the second catch statement will never execute.

 To fix the problem, reverse the order of the catch statements.


Nested try Statements Mr. Bhandare P.S.

 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 {

 Scanner in = new Scanner(System.in);  System.out.println("Array indexing wrong");


 }
 System.out.print("Enter number : ");
 x = in.nextInt();  System.out.println("Outer try end...");

 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};  }

 arr[10] = 25; //statement3  }


Mr. Bhandare P.S.

 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 is inputted as 0, statement1 will cause an exception


“Divide by zero”. So program control will directly transfer to catch
statement no.2 to take the action.

 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”.

 This will be caught by inner try’s catch clause.


 That is, the outer try’s catch clause will catch all the exception occurred
inside it.

 Remember, if the exception of “array index out of bounds” is occurred in


outer try then this will not be caught by inner try’s catch clause.
 // Nested try blocks with method Mr. Bhandare P.S.

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 introduces a method in program that causes the exception.


52
Observe the outputs.

 When the entered number from keyboard is 1, statement2 will be executed


properly and the method is called at statement3.

 In statement1 the exception of “negative array size” is occurred.

 Here, the match will not found at catch clause 1.

 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.

 However, it is possible for your program to throw an exception explicitly,


using the throw statement.

 The general form of throw is shown here:


 throw ThrowableInstance;
 Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.

 Primitive types, such as int or char, as well as non-Throwable classes,


such as String and Object, cannot be used as exceptions.
Mr. Bhandare P.S.

 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.

 The nearest enclosing try block is inspected to see if it has a catch


statement that matches the type of exception.

 If it does find a match, control is transferred to that statement.


Mr. Bhandare P.S.

55
If not, then the next enclosing try statement is inspected, and so on.

If no matching catch is found, then the default exception handler


halts the program and prints the stack trace.

Here is a sample program that creates and throws an exception.

 The handler that catches the exception rethrows it to the outer


handler.
Mr. Bhandare P.S.

 // Demonstrate throw.  catch(NullPointerException e)


56  class ThrowDemo {  {
 static void demoproc() {  System.out.println("Recaught: " + e);
 try {  }
 throw new NullPointerException("demo");  }
 } catch(NullPointerException e) {  }
 System.out.println("Caught inside
demoproc.");
 throw e; // rethrow the exception
 }
 }
 public static void main(String args[]) {
 try {
 demoproc();
 }
Mr. Bhandare P.S.

 This program gets two chances to deal with the same error. First, main( )
57
sets up an exception context and then calls demoproc( ).

 The demoproc( ) method then sets up another exception-handling context


and immediately throws a new instance of NullPointerException, which is
caught on the next line.
 The exception is then rethrown. Here is the resulting output:
 Caught inside demoproc.
 Recaught: java.lang.NullPointerException: demo
 The program also illustrates how to create one of Java’s standard exception
objects. Pay close attention to this line:
 throw new NullPointerException("demo");
Mr. Bhandare P.S.

 Here, new is used to construct an instance of NullPointerException.


58

 Many of Java’s built-in run-time exceptions have at least two


constructors: one with no parameter and one that takes a string parameter.

 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( ).

 It can also be obtained by a call to getMessage( ), which is defined by


Throwable.
 public class TestThrow1{ Mr. Bhandare P.S.

59  static void validate(int age){


 if(age<18)
 throw new ArithmeticException("not valid");
 else
 System.out.println("welcome to vote");
 }
 public static void main(String args[]){
 validate(10);
 System.out.println("rest of the code...");
 }
}
throws Mr. Bhandare P.S.

 If a method is capable of causing an exception that it does not handle, it


60
must specify this behavior so that callers of the method can guard
themselves against that exception.

 You do this by including a throws clause in the method’s declaration. A


throws clause lists the types of exceptions that a method might throw.

 This is necessary for all exceptions, except those of type Error or


RuntimeException, or any of their subclasses.

 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.

 This is the general form of a method declaration that includes a throws


61
clause:
type method-name(parameter-list) throws exception-list
{
 // body of method
}

 Here, exception-list is a comma-separated list of the exceptions that a


method can throw.
 // This program contains an error and will not compile. 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.

 To make this example compile, you need to make two changes.


63

 First, you need to declare that throwOne( ) throws


IllegalAccessException. Second, main( ) must define a try / catch
statement that catches this exception.

 Here is the output generated by running this example program:


inside throwOne
caught java.lang.IllegalAccessException: demo
Mr. Bhandare P.S.

 // This is now correct.


64
 class ThrowsDemo {
 static void throwOne() throws IllegalAccessException {
 System.out.println("Inside throwOne.");
 throw new IllegalAccessException("demo");
 }
 public static void main(String args[]) {
 try {
 throwOne();
 } catch (IllegalAccessException e) {
 System.out.println("Caught " + e);
 }
 }
 }
 import java.io.*; 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.

66 Difference between throw and throws in Java


No. throw throws
Java throw keyword is used to
1) Java throws keyword is used to declare an exception.
explicitly throw an exception.

Checked exception cannot be


2) Checked exception can be propagated with throws.
propagated using throw only.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

You can declare multiple exceptions e.g. public void


5) You cannot throw multiple exceptions.
method()throws IOException,SQLException.
Java Exception propagation Mr. Bhandare P.S.

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.

 This is called exception propagation.

By default Unchecked Exceptions are forwarded in calling chain


(propagated).
 class TestExceptionPropagation1{
Mr. Bhandare P.S.
 void m(){
68  int data=50/0;
 }
 void n(){
 m();
 }
 void p(){
 try{
 n();
 }catch(Exception e){System.out.println("exception handled");}
 }
 public static void main(String args[]){
 TestExceptionPropagation1 obj=new TestExceptionPropagation1();
 obj.p();
 System.out.println("normal flow...");
 } }
Mr. Bhandare P.S.

69

 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.

 Exception can be handled in any method in call stack either in main()


method,p() method,n() method or m() method.
Mr. Bhandare P.S.
By default, Checked Exceptions are not forwarded in calling chain
70 (propagated).
 class TestExceptionPropagation2{  public static void main(String args[]){
 void m(){  TestExceptionPropagation2 obj=new TestExcepti
onPropagation2();
 throw new java.io.IOException("device error");
//checked exception  obj.p();
 }  System.out.println("normal flow");
 void n(){  }
 m();  }
 }
 void p(){
 try{
 n();
 }catch(Exception e){System.out.println("exceptio
n handeled");}
 }
finally Mr. Bhandare P.S.

 When exceptions are thrown, execution in a method takes a rather abrupt,


71 nonlinear path that alters the normal flow through the method.

 Depending upon how the method is coded, it is even possible for an


exception to cause the method to return prematurely.

 This could be a problem in some methods.

 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.

 The finally keyword is designed to address this contingency.


Mr. Bhandare P.S.

 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.

 The finally block will execute whether or not an exception is thrown.

 If an exception is thrown, the finally block will execute even if no catch


statement matches the exception.

 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.

 The finally clause is optional.

 However, each try statement requires at least one catch or a finally


clause.
Mr. Bhandare P.S.

 The try-catch-finally of try-finally construct can be created as,


74
 try
 {
 .......
 }
 catch(....) //multiple catch are allowed
 {
 .......
 }
 finally
 {
 .......
 }
Mr. Bhandare P.S.

75
 try
 {
 .......
 }
 finally
 {
 .......
 }
Mr. Bhandare P.S.

 class FinallyDemo {  // Return from within a try block.


76
 // Throw an exception out of the  static void procB() {
method.  try {
 static void procA() {  System.out.println("inside procB");
 try {  return;
 System.out.println("inside procA");  } finally {
 throw new  System.out.println("procB's finally");
RuntimeException("demo");
 }
 }
 }
 finally {
 System.out.println("procA's finally");
 }
 }
Mr. Bhandare P.S.

 // Execute a try block normally.  }


77
 static void procC() {  catch (Exception e)
 try { {
 System.out.println("inside procC");  System.out.println("Exception caught");
 } finally {  }
 System.out.println("procC's 
finally");  procB();
 }  procC();
 }  }
 }
 public static void main(String args[]) {
 try {
 procA();
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.

 However, the finally block is still executed.

 Here is the output generated by the preceding program:


Difference between final, finally and finalize Mr. Bhandare P.S.

79

No. final finally finalize

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.

2) Final is a keyword. Finally is a block. Finalize is a method.


Mr. Bhandare P.S.

80 Java final example

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.

83  Inside the standard package java.lang, Java defines several exception


classes. A few have been used by the preceding examples.

 The most general of these exceptions are subclasses of the standard type
RuntimeException.

 As previously explained, these exceptions need not be included in any


method’s throws list.

 In the language of Java, these are called unchecked exceptions because


the compiler does not check to see if a method handles or throws these
exceptions.
 The unchecked exceptions defined in java.lang are listed in Table Mr. Bhandare P.S.

84 Exception Meaning / When occurred


ArithmeticException Arithmetic error, such as divide by zero.

ArrayIndexOutOfBoundsException Array index is out of bounds.


ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid casting of classes
IllegalArgumentException Illegal argument used to invoke a method
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out of bounds
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric format
SecurityException Attempt to violate security
StringIndexOutOfBounds Exception Attempt to index outside the bounds of a string

UnsupportedOperationException An unsupported operation was encountered


Mr. Bhandare P.S.

 Table lists those exceptions defined by java.lang that must be included in a


85 method’s throws list if that method can generate one of these exceptions and
does not handle it itself.

 These are called checked exceptions. In addition to the exceptions in


java.lang, Java defines several more that relate to its other standard packages
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface.

IllegalAccessException Access to a class is denied.


InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
ReflectiveOperationException Superclass of reflection-related exceptions.
Creating Your Own Exception Subclasses Mr. Bhandare P.S.

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

 Your subclasses don’t need to actually implement anything—it is their


existence in the type system that allows you to use them as exceptions.

 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.

 Exception defines four public constructors.


Exception( )
Exception(String msg)
Exception(String message, Throwable cause)
Exception(Throwable cause)

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.

 Although specifying a description when an exception is created is often


88
useful, sometimes it is better to override toString( ).

 Here’s why: The version of toString( ) defined by Throwable (and


inherited by Exception) first displays the name of the exception followed
by a colon, which is then followed by your description.

 By overriding toString( ), you can prevent the exception name and colon
from being displayed.

 This makes for a cleaner output, which is desirable in some cases.


Mr. Bhandare P.S.

 Java has defined a lot of Exception and Error classes for different
89
conditions.

 But many times it is required in some conditions that we want to create


your own exception types to handle situations specific to our applications.

 This is quite easy to do. We just have to define a subclass of Exception


(which is a subclass of Throwable).

 Our subclasses don’t need to actually implement anything. It is their


existence in the type system that allows us to use them as exceptions.
Mr. Bhandare P.S.

 The Exception class does not define any methods of its own.
90

 It inherits all the methods provided by class Throwable.

 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.

 // Creating our own exception.


91
 class NegativeOutputException extends Exception
 {
 private int det;
 NegativeOutputException(int a)
 {
 det = a;
 }
 public String toString()
 {
 return "NegativeOutputException["+det+"]";
 }
 }
 class OwnException  { 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.

 Name of the defined exception is NegativeOutputException. The method


toString( ) has been overridden to print our own custom message with
exception class.

 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.

 Now exception is thrown using the throw clause.

 This exception is caught by catch clause.

 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.

 The chained exception feature allows you to associate another exception


with an exception.

 This second exception describes the cause of the first exception.

 For example, imagine a situation in which a method throws an


ArithmeticException because of an attempt to divide by zero.

 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.

 Although the method must certainly throw an ArithmeticException,


96 since that is the error that occurred, you might also want to let the calling
code know that the underlying cause was an I/O error.

 Chained exceptions let you handle this, and any other situation in which
layers of exceptions exist.

 To allow chained exceptions, two constructors and two methods were


added to Throwable.

 The constructors are shown here:


 Throwable(Throwable causeExc)
 Throwable(String msg, Throwable causeExc)
Mr. Bhandare P.S.

 In the first form, causeExc is the exception that causes the current
97
exception.

 That is, causeExc is the underlying reason that an exception occurred.

 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.

 If there is no underlying exception, null is returned. The initCause( )


method associates causeExc with the invoking exception and returns a
reference to the 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.

 The first automates the process of releasing a resource, such as a file,


when it is no longer needed.

 It is based on an expanded form of the try statement called try-with-


resources.

 The second feature is called multi-catch, and the third is sometimes


referred to as final rethrow or more precise rethrow.
 These two features are described here.
Mr. Bhandare P.S.

 The multi-catch feature allows two or more exceptions to be caught by the


102 same catch clause.

 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.

104 Exception handling provides a powerful mechanism for controlling


complex programs that have many dynamic run-time characteristics.

It is important to think of try, throw, and catch as clean ways to


handle errors and unusual boundary conditions in your program’s
logic.

Unlike some other languages in which error return codes are used to
indicate failure, Java uses exceptions.

Thus, when a method can fail, have it throw an exception.


Mr. Bhandare P.S.

105
This is a cleaner way to handle failure modes.

One last point: Java’s exception-handling statements should not be


considered a general mechanism for nonlocal branching.

 If you do so, it will only confuse your code and make it hard to
maintain.
Multithreaded Programming Mr. Bhandare P.S.

106  Java provides built-in support for multithreaded programming.

 A multithreaded program contains two or more parts that can run


concurrently.

 Each part of such a program is called a thread, and each thread defines a
separate path of execution.

 Thus, multithreading is a specialized form of multitasking.

 there are two distinct types of multitasking: process-based and thread-


based.
Mr. Bhandare P.S.

 It is important to understand the difference between the two.


107

 For many readers, process-based multitasking is the more familiar form.

 A process is, in essence, a program that is executing.

 Thus, process-based multitasking is the feature that allows your computer


to run two or more programs concurrently.

 For example, process-based multitasking enables you to run the Java


compiler at the same time that you are using a text editor or visiting a web
site.
Mr. Bhandare P.S.

 In a thread-based multitasking environment, the thread is the smallest unit


108
of dispatchable code.

 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.

 Multitasking threads require less overhead than multitasking processes.


109

 Processes are heavyweight tasks that require their own separate address
spaces.

 Inter-process communication is expensive and limited. Context switching


from one process to another is also costly.

 Threads are lightweight. They share the same address space and
cooperatively share the same heavyweight process.

 Inter-thread communication is inexpensive, and context switching from


one thread to the next is low cost.
Mr. Bhandare P.S.

 While Java programs make use of process-based multitasking


110 environments, process-based multitasking is not under the control of
Java.

 But, multithreaded multitasking is.

 Multithreading enables us to write very efficient programs that make


maximum use of the CPU, because idle time can be kept to a minimum.

 We can divide a program into threads and execute them parallel.

 If we have programmed for operating systems such as Windows 98 or


Windows 2000, then it is very easy to learn multithreaded programming.
 When a program contains multiple flows of control it is known Mr.asBhandare P.S.
multithreaded program.
111

 Figure illustrates a Java program containing four different threads,


one main and three others.
Mr. Bhandare P.S.

 In a Java program a main thread is actually a main thread module which is


112
the creating and starting point for all other threads A, B and C.

 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 interpreter handles the context switching of control among


113
threads in such a way that they runs concurrently.

 In essence, Java makes the use of operating system’s multithreading


ability.

 That is, if a multithreaded program running under Windows platform,


does not guarantee that it will give same output on Linux platform.

 Threads are extensively used in Java-enabled browsers such as HotJava.


The Java Thread Model 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.

 In fact, Java uses threads to enable the entire environment to be


asynchronous.

 This helps reduce inefficiency by preventing the waste of CPU cycles.

 The value of a multithreaded environment is best understood in contrast


to its counterpart.

 Single-threaded systems use an approach called an event loop with


polling.
Mr. Bhandare P.S.

 In this model, a single thread of control runs in an infinite loop, polling a


115 single event queue to decide what to do next.

 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.

 In general, in a single-threaded environment, when a thread blocks (that


116
is, suspends execution) because it is waiting for some resource, the entire
program stops running.

 The benefit of Java’s multithreading is that the main loop/polling


mechanism is eliminated.

 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.

 Multithreading allows animation loops to sleep for a second between each


117
frame without causing the whole system to pause.

 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.

 Of course, single-core systems are still in widespread use.

 It is important to understand that Java’s multithreading features work in


both types of systems.
Mr. Bhandare P.S.

 In a single-core system, concurrently executing threads share the CPU,


118
with each thread receiving a slice of CPU time.

 Therefore, in a single-core system, two or more threads do not actually


run at the same time, but idle CPU time is utilized.

 However, in multi-core systems, it is possible for two or more threads to


actually execute simultaneously.

 Threads exist in several states. Here is a general description. A thread can


be running.
Mr. Bhandare P.S.

 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.

 A suspended thread can then be resumed, allowing it to pick up where it


left off.

 A thread can be blocked when waiting for a resource.

 At any time, a thread can be terminated, which halts its execution


immediately.

 Once terminated, a thread cannot be resumed.


Life cycle of thread Mr. Bhandare P.S.

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

 A thread is always in one of these five states.

 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.

 If we attempt to perform any other operation, the exception will be


thrown.
Runnable state Mr. Bhandare P.S.

 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.

 This process of assigning time to threads is known as time-slicing. If we


want a thread to relinquish control to another thread of equal priority, a
yield( ) method can be used.
Running state Mr. Bhandare P.S.

124  When the processor has given time to the thread for its execution then the
thread is said to be in running state.

 The thread runs until it relinquishes control to its own or it is preempted


by a higher priority thread.

 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.

 This happens when the thread is suspended, sleeping or waiting in order


to satisfy certain requirements.

 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.

 A thread can be killed as soon as it is born or while it is running or even


when it is in blocked state.
The Thread class and Runnable interface Mr. Bhandare P.S.

128  Java’s multithreading system is built upon the Thread class, its methods,
and its companion interface called Runnable.

 Thread class encapsulates a thread of execution.

 To create a new thread, program will either extend Thread or implement


the Runnable interface.

 The Thread class defines several methods that help manage threads.
Mr. Bhandare P.S.

129
Method Meaning

getName Obtain a thread’s name.

getPriority Obtain a thread’s priority.

isAlive Determine if a thread is still running.

join Wait for a thread to terminate.

run Entry point for the thread.

sleep Suspend a thread for a period of time.

start Start a thread by calling its run method.


The Main Thread Mr. Bhandare P.S.

 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.

 The main thread is important for two reasons:


It is the thread from which other “child” threads will be spawned.
Often, it must be the last thread to finish execution because it performs
various shutdown actions.

Although the main thread is created automatically when your program


is started, it can be controlled through a Thread object.
Mr. Bhandare P.S.

 To do so, you must obtain a reference to it by calling the method


131
currentThread( ), which is a public static member of Thread.

 Its general form is shown here:


 static Thread currentThread( )

 This method returns a reference to the thread in which it is called.

 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.

 class CurrentThreadDemo {  } catch (InterruptedException e) {


132
 public static void main(String args[])  System.out.println("Main thread
interrupted");
 {
 Thread t = Thread.currentThread();  }

 System.out.println("Current thread: " + t);  }


 }
 // change the name of the thread
 t.setName("My Thread");
 System.out.println("After name change: " + t);
 try {
 for(int n = 5; n > 0; n--) {
 System.out.println(n);
 Thread.sleep(1000);
 }
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.

 Next, the program displays information about the thread.

 The program then calls setName( ) to change the internal name of the
thread.

 Information about the thread is then redisplayed.

 Next, a loop counts down from five, pausing one second between each
line.
Mr. Bhandare P.S.

 The pause is accomplished by the sleep( ) method.


134

 The argument to sleep( ) specifies the delay period in milliseconds.

 Notice the try/catch block around this loop.

 The sleep( ) method in Thread might throw an InterruptedException.

 A thread group is a data structure that controls the state of a collection of


threads as a whole.
Mr. Bhandare P.S.
 This time, the new name of the thread is displayed.
135  Let’s look more closely at the methods defined by Thread that are used in
the program.

 The sleep( ) method causes the thread from which it is called to suspend
execution for the specified period of milliseconds.

 Its general form is shown here:


 static void sleep(long milliseconds) throws InterruptedException

 The number of milliseconds to suspend is specified in milliseconds.


 This method may throw an InterruptedException.
Mr. Bhandare P.S.

 As the preceding program shows, you can set the name of a thread by
136 using setName( ).

 You can obtain the name of a thread by calling getName( ).

 These methods are members of the Thread class and are declared like this:
final void setName(String threadName)
final String getName( )

 Here, threadName specifies the name of the thread


Creating a Thread Mr. Bhandare P.S.

137  In the most general sense, you create a thread by instantiating an object of
type Thread.

 Java defines two ways in which this can be accomplished:

1.You can implement the Runnable interface.


2.You can extend the Thread class, itself.

 The following two sections look at each method, in turn.


Implementing Runnable Mr. Bhandare P.S.

 The easiest way to create a thread is to create a class that implements the
138
Runnable interface.

 Runnable abstracts a unit of executable code.

 You can construct a thread on any object that implements Runnable.

 To implement Runnable, a class need only implement a single method


called run( ), which is declared like this:
public void run( )
 Inside run( ), you will define the code that constitutes the new thread
Mr. Bhandare P.S.

 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.

 This thread will end when run( ) returns.

 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.

 // Create a second thread.  Thread.sleep(500);


141  class NewThread implements Runnable {  }
 Thread t;  } catch (InterruptedException e) {
 NewThread() {  System.out.println("Child interrupted.");
 // Create a new, second thread  }
 t = new Thread(this, "Demo Thread");  System.out.println("Exiting child
 System.out.println("Child thread: " + t); thread.");

 t.start(); // Start the thread  }


 }
 }
 // This is the entry point for the second thread.
 public void run() {
 try {
 for(int i = 5; i > 0; i--) {
 System.out.println("Child Thread: " + i);
 class ThreadDemo { Mr. Bhandare P.S.

 public static void main(String args[ ] ) {


142
 new NewThread(); // create a new thread
 try {
 for(int i = 5; i > 0; i--) {
 System.out.println("Main Thread: " + i);
 Thread.sleep(1000);
 }
 } catch (InterruptedException e) {

 System.out.println("Main thread interrupted.");
 }
 System.out.println("Main thread exiting.");
 }
 }
Extending Thread 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.

 It must also call start( ) to begin execution of the new thread.

 Here is the preceding program rewritten to extend Thread:


Mr. Bhandare P.S.

 // Create a second thread by extending  System.out.println("Child Thread: " + i);


144 Thread  Thread.sleep(500);
 class NewThread extends Thread {
 }
 NewThread() {  } catch (InterruptedException e) {
 // Create a new, second thread  System.out.println("Child interrupted.");
 super("Demo Thread");
 }
 System.out.println("Child thread: " + this);  System.out.println("Exiting child
 start(); // Start the thread thread.");
 }  }
 // This is the entry point for the second  }
thread.
 public void run() {
 try {
 for(int i = 5; i > 0; i--) {
 class ExtendThread { Mr. Bhandare P.S.

 public static void main(String args[]) {


145
 new NewThread(); // create a new thread
 try {
 for(int i = 5; i > 0; i--) {
 System.out.println("Main Thread: " + i);
 Thread.sleep(1000);
 }
 } catch (InterruptedException e) {
 System.out.println("Main thread interrupted.");
 }
 System.out.println("Main thread exiting.");
 }
 }
Creating Multiple Threads Mr. Bhandare P.S.

 // Create multiple threads.  try {


146
 class NewThread implements Runnable for(int i = 5; i > 0; i--) {
{  System.out.println(name + ": " + i);
 String name; // name of thread  Thread.sleep(1000);
 Thread t;  }
 NewThread(String threadname) {  } catch (InterruptedException e) {
 name = threadname;  System.out.println(name +
 t = new Thread(this, name); "Interrupted");
 System.out.println("New thread: " + t);  }
 t.start(); // Start the thread  System.out.println(name + "
 } exiting.");

 // This is the entry point for thread.  }

 public void run() { }


Mr. Bhandare P.S.

 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.

 In the preceding examples, this is accomplished by calling sleep( ) within


main( ), with a long enough delay to ensure that all child threads terminate
prior to the main thread.

 However, this is hardly a satisfactory solution, and it also raises a larger


question: How can one thread know when another thread has ended?

 Fortunately, Thread provides a means by which you can answer this


question.
Mr. Bhandare P.S.
 Two ways exist to determine whether a thread has finished.
149

 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:

 final void join( ) throws InterruptedException


Mr. Bhandare P.S.

 This method waits until the thread on which it is called terminates.


150

 Its name comes from the concept of the calling thread waiting until the
specified thread joins it.

 Additional forms of join( ) allow you to specify a maximum amount of time


that you want to wait for the specified thread to terminate.

 Here is an improved version of the preceding example that uses join( ) to


ensure that the main thread is the last to stop.

 It also demonstrates the isAlive( ) method.


Mr. Bhandare P.S.

 class NewThread implements Runnable {  }


151  String name;  } catch (InterruptedException e) {
 Thread t;  System.out.println(name + "
 NewThread(String threadname) { interrupted.");

 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.

 public static void main(String args[]) {  } catch (InterruptedException e) {


152
 NewThread ob1 = new NewThread("One");  System.out.println("Main thread Interrupted");
 NewThread ob2 = new NewThread("Two");  }
 NewThread ob3 = new NewThread("Three");  System.out.println("Thread One is alive: "
 ystem.out.println("Thread One is alive: "  + ob1.t.isAlive());
 + ob1.t.isAlive());  System.out.println("Thread Two is alive: "
 System.out.println("Thread Two is alive: "  + ob2.t.isAlive());
 + ob2.t.isAlive());  System.out.println("Thread Three is alive: "
 System.out.println("Thread Three is alive: "  + ob3.t.isAlive());
 + ob3.t.isAlive());  System.out.println("Main thread exiting.");
 // wait for threads to finish  }
 try {  }
 System.out.println("Waiting for threads to finish.");
 ob1.t.join();
 ob2.t.join();
Thread priorities Mr. Bhandare P.S.

 Thread priorities are used by the thread scheduler to decide when each
153
thread should be allowed to run.

 In theory, over a given period of time, higher-priority threads get more


CPU time than lower-priority threads.

 In practice, the amount of CPU time that a thread gets often depends on
several factors besides its priority.

 A higher-priority thread can also preempt a lower-priority one.

 For instance, when a lower-priority thread is running and a higher-priority


thread resumes it will preempt the lower-priority thread.
Mr. Bhandare P.S.

 Threads of equal priority should get equal access to the CPU.


154

 To set a thread’s priority, use the setPriority( ) method, which is a member


of Thread.

 This is its general form:


 final void setPriority(int level)

 Here, level specifies the new priority setting for the calling thread.

 The value of level must be within the range MIN_PRIORITY and


MAX_PRIORITY.
 Currently, these values are 1 and 10, respectively. Mr. Bhandare P.S.

155
 To return a thread to default priority, specify NORM_PRIORITY, which is
currently 5.

 These priorities are defined as static final variables within Thread.

 You can obtain the current priority setting by calling the getPriority( )
method of Thread, shown here:
 final int getPriority( )

 Implementations of Java may have radically different behavior when it


comes to scheduling
Mr. Bhandare P.S.

 // Assigning Thread priorities.  System.out.println("Thread: " + n);


156  class NewThread implements Runnable {  Thread.sleep(10); //statement8
 Thread t;  }catch(InterruptedException e){ }
 String n;  }
 public NewThread(int pri, String name) {  }
 n = name;  public void start()
 t = new Thread(this, name);  {
 t.setPriority(pri); //statement7  t.start();
 System.out.println("Thread: " + t);  }
 }  }
 public void run() {
 for(int i = 100;; i--)
 {
 try {
Mr. Bhandare P.S.

 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.

 In program, three different threads are created including main thread.


158

 The statement1 assigns highest priority to the main thread.

 The statement2 and statement3 creates the thread named “ABC” and
“XYZ” with priorities 7 and 3 respectively.

 So the thread “ABC” is having higher priority than “XYZ”. That is


reflected in the output also. Actually, this program will run into infinity.

 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.

 Instead of directly giving the numbers we can use the constants,


159 NORM_PRIORITY, MAX_PRIORITY and MIN_PRIORITY etc.

 This concept is thoroughly useful in developing the application Java


program for operating system.

 Remember we will get different output of the same program on Linux or


any other operating system.

 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.

 The process by which this is achieved is called synchronization.

 As you will see, Java provides unique, language-level support for it.

 Key to synchronization is the concept of the monitor.

 A monitor is an object that is used as a mutually exclusive lock.


Mr. Bhandare P.S.

 Only one thread can own a monitor at a given time.


161

 When a thread acquires a lock, it is said to have entered the monitor.

 All other threads attempting to enter the locked monitor will be suspended
until the first thread exits the monitor.

 These other threads are said to be waiting for the monitor.

 A thread that owns a monitor can reenter the same monitor if it so desires
Mr. Bhandare P.S.

 In Java, all objects have a lock including arrays.


162

 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.

 The object lock mechanism forces the following rules of


163
synchronization:

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.

 If a thread cannot immediately acquire the object lock, it is blocked, that


is, it must wait for the lock to become available.
Mr. Bhandare P.S.

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.

 There are two different ways in which execution of code can be


synchronized:
synchronized methods
synchronized blocks
Synchronized methods Mr. Bhandare P.S.

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’.

 When a thread is running inside a synchronized method, all other threads


that try to call it (or any other synchronized method) on the same instance
they have to wait.

 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.

166 class Table{


void printTable(int n){//method not synchronized
 for(int i=1;i<=5;i++){
 System.out.println(n*i);
 try{
 Thread.sleep(400);
 }catch(Exception e){System.out.println(e);}
 }
 }
}
Mr. Bhandare P.S.
 class MyThread1 extends Thread{  class MyThread2 extends Thread{
167  Table t;  Table t;
 MyThread1(Table t){  MyThread2(Table t){
 this.t=t;  this.t=t;
} }
 public void run(){  public void run(){
 t.printTable(5);  t.printTable(100);
} }
 }
}
class TestSynchronization1{ 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.

 So, it resulted in the mixed-up output of the three message strings.

 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.

 Using synchronized methods is very easy and effective means of


172
synchronization. But it will not work in all cases.

 For example, if we want to make a synchronized access to particular


objects, that is all its member variables and methods then synchronized
blocks can be used.

 The form of using the synchronized blocks is as follows:


 synchronized(object)
{
 // statements to be synchronized
}
Mr. Bhandare P.S.

 Here, ‘object’ is a reference to the object being synchronized.


173

 A synchronized block ensures that a call to a method that is a member of


object occurs only after the current thread has successfully entered object’s
lock.

 If we want to synchronize the current object and its methods then the
‘this’ keyword can be used instead of ‘object’.

 Now we will modify the previous program with block synchronization.


 class Table{ Mr. Bhandare P.S.

174  void printTable(int n){


 synchronized(this){//synchronized block
 for(int i=1;i<=5;i++){
 System.out.println(n*i);
 try{
 Thread.sleep(400);
 }catch(Exception e){System.out.println(e);}
 }
 }
 }//end of the method
}
Mr. Bhandare P.S.

 class MyThread1 extends Thread{  class MyThread2 extends Thread{


175
 Table t;  Table t;
 MyThread1(Table t){  MyThread2(Table t){
 this.t=t;  this.t=t;
} }
 public void run(){  public void run(){
 t.printTable(5);  t.printTable(100);
} }
} }
Mr. Bhandare P.S.

176  public class TestSynchronizedBlock1


{
 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:
177
5
 100
 10
 200
 15
 300
 20
 400
 25

 500
Mr. Bhandare P.S.

 This output is too random and disturbed.


178

 Synchronized blocks can also be specified on a class lock:

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.

 For example, a static synchronized method display( ) in class A is


179
equivalent to the following declaration:

 static void display( )


{
 synchronized (A.class)
{
 // synchronized block on class A
 // ......
 }
}
Mr. Bhandare P.S.

 In short, a thread can hold a lock on the object,


180

1. by executing a synchronized instance method of the object by executing


the body of a synchronized block that synchronizes on the object

2. by executing a synchronized static method of a class


Interthread Communication Mr. Bhandare P.S.

181 Using wait( ) and notify( )


 To avoid polling, Java includes an elegant interprocess communication
mechanism via the wait( ), notify( ), and notifyAll( ) methods.

 These methods are implemented as final methods in Object, so all classes


have them.

 All three methods can be called only from within a synchronized context.

 Waiting and notifying provide means of communication between threads


that synchronize on the same object.
Mr. Bhandare P.S.

 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 referred as inter-thread communication methods.

 These methods are used to avoid the polling. Polling is usually implemented
by a loop that is used to check some condition repeatedly.

 Once the condition is true, suitable action is taken.


Mr. Bhandare P.S.

 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.

 This situation is undesirable.


184

 We need to design it in such a way that when producer has produced


some data consumer consumes it.

 This process goes on in sequence.

 In order to do this, we need to establish proper communication between


the producer and consumer threads.

 This can be done by wait( ) & notify( ) methods.


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.

 Here, the highest priority thread will run first.


Mr. Bhandare P.S.

 These methods are declared within Object, as shown here:


186
final void wait( ) throws InterruptedException
final void notify( )
final void notify All( )

 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.

 class Queue {  synchronized void produce(int n) {


188
 int num;  if(isSet) {
 boolean isSet = false;  try{
 synchronized int consume() {  wait();
 if(!isSet) {  }catch(Exception e) { }
 try{  }
 wait();  num = n;
 }catch(Exception e) { }  System.out.println("Produced: " + num);
 }  isSet = true;
 System.out.println("Consumed: " + num);  notify();
 isSet = false;  }
 notify();  }
 return num;
 }
Mr. Bhandare P.S.

 class Producer implements Runnable {


189
 Queue q;
 Producer(Queue q)
 {
 this.q = q;
 new Thread(this, "Producer").start();
 }
 public void run()
 {
 int i = 0;
 while(i<5)
 q.produce(++i);
 }
 }
Mr. Bhandare P.S.

 class Consumer implements Runnable


190
 {
 Queue q;
 Consumer(Queue q)
 {
 this.q = q;
 new Thread(this, "Consumer").start();
 }
 public void run()
 {
 while(q.consume()<5);
 }
 }
Mr. Bhandare P.S.

191  class ProConUsed


 {
 public static void main(String args[])
 {
 Queue q = new Queue();
 new Producer(q);
 new Consumer(q);
}
 }
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.

 Observe program. Inside consume( ), wait( ) is called.


193

 This causes its execution to suspend until the Producer notifies you that
some data is ready.

 When this happens, execution inside consume( ) resumes.

 After the data has been obtained, consume( ) calls notify( ).

 This tells Producer that it is now okay to put more data in the queue.

 Inside produce( ), wait( ) suspends execution until the Consumer has


removed the item from the queue.
Mr. Bhandare P.S.

 When execution resumes, the next item of data is put in the queue, and
194
notify( ) is called.

 This tells the Consumer that it should now remove it.

 Here the variable ‘isSet’ plays an important role to check whether the
consume( ) or produce( ) has finished their task properly.

 The output obtained shown clean and synchronized behavior of producer-


consumer problem.
E.g  class Customer{ Mr. Bhandare P.S.

195  int amount=10000;


 synchronized void withdraw(int amount)
{
 System.out.println("going to withdraw...");
 if(this.amount<amount)
{
 System.out.println("Less balance; waiting for deposit...");
 try{wait();}catch(Exception e){}
}
 this.amount-=amount;
 System.out.println("withdraw completed...");
}
Mr. Bhandare P.S.

 synchronized void deposit(int amount)  new Thread(){


196
{  public void run(){
 System.out.println("going to deposit...")  c.withdraw(15000);}
;  }.start();
 this.amount+=amount;  new Thread(){
 System.out.println("deposit completed...  public void run(){c.deposit(10000);}
");
 }.start();
 notify();
 }
}
}
}
 class Test{
 public static void main(String args[]){
 final Customer c=new Customer();
Difference between wait and sleep? Mr. Bhandare P.S.

197

wait() sleep()

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

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

is the non-static method is the static method

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


notifyAll() methods completed.
Deadlock Mr. Bhandare P.S.

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.

For example, suppose one thread enters the monitor on


object X and another thread enters the monitor on object Y.

If the thread in X tries to call any synchronized method on


Y, it will block as expected.
Mr. Bhandare P.S.

 However, if the thread in Y, in turn, tries to call any synchronized method


199
on X, the thread waits forever, because to access X, it would have to
release its own lock on Y so that the first thread could complete.

 Deadlock is a difficult error to debug for two reasons:

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.

 To understand deadlock fully, it is useful to see it in action.


200

 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.

 // An example of deadlock. B.last()");


201  class A {  b.last();
 synchronized void foo(B b) {  }
 String name = 
Thread.currentThread().getName();  synchronized void last() {
 System.out.println(name + " entered
 System.out.println("Inside A.last");
A.foo");
 }

 }
 try {
 Thread.sleep(1000);
 } catch(Exception e) {
 System.out.println("A Interrupted");
 }

 System.out.println(name + " trying to call
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.

 class Deadlock implements Runnable {  }


203
 A a = new A(); 
 B b = new B();  public void run() {
  b.bar(a); // get lock on b in other thread.
 Deadlock() {  System.out.println("Back in other
thread");

Thread.currentThread().setName("MainThr  }
ead"); 
 Thread t = new Thread(this,  public static void main(String args[]) {
"RacingThread");
 new Deadlock();
 t.start();
 }

 }
 a.foo(b); // get lock on a in this thread.
 System.out.println("Back in main
thread");
Banking example Mr. Bhandare P.S.

204 class Customer{


int amount=10000;
 synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
 if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

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.

public static void main(String[] args) {


208
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
 Thread t2 = new Thread() { Mr. Bhandare P.S.

 public void run() {


209
 synchronized (resource2) {
 System.out.println("Thread 2: locked resource 2");
 try { Thread.sleep(100);} catch (Exception e) {}
 synchronized (resource1) {
 System.out.println("Thread 2: locked resource 1");
 }
 }
 }
 };
 t1.start();
 t2.start();
 }
}
Static synchronization 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);
} }
}

class MyThread2 extends Thread{ class MyThread4 extends Thread{


public void run(){ public void run(){
Table.printTable(10); Table.printTable(1000);
} }
} }
Mr. Bhandare P.S.

public class TestSynchronization4


212
{
public static void main(String t[])
{
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Summer 2017 Mr. Bhandare P.S.

213

1. What is thread? Draw thread life cycle diagram in Java. (4M)


2. What is thread priority? Write default priority values and methods to change
them. (4M)
3. What is exception? WAP to accept a password from the user and throw
“Authentication Failure” exception if the password is incorrect. (8M)
4. Write a program to create two threads, one to print numbers in original
order and other in reverse order from 1 to 10. (8M)
Winter 2016 Mr. Bhandare P.S.

214
1. What is an exception ? How it is handled ? Give suitable example.
(4M)

2. What is synchronization ? When do we use it ? Explain


synchronization of two threads. (4M)

3. Write a thread program for implementing the ‘Runnable interface’.


(8M)

4. Define an exception called ‘No match Exception’ that is thrown when


a string is not equal to “MSBTE”. Write program. (8M)
Summer 2016 Mr. Bhandare P.S.

215

1. Describe life cycle of thread.(4M)

2. Describe use of ‘throws’ with suitable example.(4M)

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

3. Write a program to accept password from user and throw ‘Authentication


failure’ exception if password is incorrect.(8M)

4. Explain life cycle of thread with a neat diagram. (8M)


Summer 2015 Mr. Bhandare P.S.

217

1. Define an exception. How it is handled ?(4M)

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)

2. Describe life cycle of thread?(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)

You might also like