Unit-IV
EXCEPTION HANDLING
N.RUBA
ASST.PROF/COMPUTER APPLICATIONS
BON SECOURS COLLEGE FOR WOMEN,
THANJAVUR.
Exception handling
 Exception handling is one of the most important feature of java programming
that allows us to handle the runtime errors caused by exceptions.
 What is an exception?
 An exception is an event that may cause abnormal termination of the
program during its execution.
 An Exception is an unwanted event that interrupts the normal flow of the
program. When an exception occurs program execution gets terminated. In
such cases we get a system generated error message.
 The good thing about exceptions is that they can be handled in Java. By
handling the exceptions we can provide a meaningful message to the user
about the issue rather than a system generated message, which may not be
understandable to a user.
Why an exception occurs?
 There can be several reasons that can cause a program to throw exception.
 For example: Opening a non-existing file in your program, Network connection problem, bad
input data provided by user etc.
Exception handler
 Is a piece of code used to deal with to exceptions, either to fix the errors or abort execution in a
sophisticated way.
 In java catch block is used to handle exceptions that are raised during program execution.
Exception Handling
 If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user. For example look at the
system generated exception below:
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see
whether the programmer has handled them or not.
If these exceptions are not handled/declared in the program, you will get compilation error
. For example,
SQLException,
IOException,
ClassNotFoundException etc.
Unchecked Exceptions
 Runtime Exceptions are also known as Unchecked Exceptions. These
exceptions are not checked at compile-time
 so compiler does not check whether the programmer has handled them or not
but it’s the responsibility of the programmer
 to handle these exceptions and provide a safe exit.
 For example,
• ArithmeticException,
• NullPointerException,
• ArrayIndexOutOfBoundsException etc.
Advantage of exception handling
 Exception handling ensures that the flow of the program doesn’t break when
an exception occurs.
Difference between error and exception
 Errors indicate that something severe enough has gone wrong, the application
should crash rather than try to handle the error.
 Exceptions are events that occurs in the code. A programmer can handle such
conditions and take necessary corrective actions.
Constructors and methods in throwable
class
Constructors
There are four constructors in the Throwable class:
 • Throwable ()
 • Throwable (String message)
 • Throwable (String message, Throwable cause)
 • Throwable (Throwable cause)
The first two allow constructing an exception object with or without a String
message encapsulated in the object.
Methods
 There are several methods in the Throwable class. Three useful methods of
the Throwable class that provide information about an exception are the
following:
 • getMessage (): Returns the message that was encapsulated when the object
was initiated. It returns null, if there is no message.
 • toString(): returns a brief description about the exception of throwable
object.
 • printStacktrace (): prints the stack trace.
StackTrace is a list of the methods executed in sequence that lead to the
exception and it is typically used to show the (unhandled) run-time errors on the
screen.
Methods of throwable class
• fillinStackTrace ()
• getStackTrace ()
• printStackTrace ()
• setStackTrace (Stack TraceElement [] stack Trace)
When an exceptional condition occurs within a method, the method may instantiate an exception
object and hand it to the run-time system to deal with it. This is called throwing an exception.
Handling exception in java
 try
 catch
 finally
 throw
 throws
Try catch example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e)
{System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Finally -syntax
try
{
//Statements that may cause an exception
}
catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
Nested try
class NestedTry {
// main method
public static void main(String args[])
{
// Main try block
try {
// initializing array
int a[] = { 1, 2, 3, 4, 5 };
// trying to print element at index 5
System.out.println(a[5]);
// try-block2 inside another try block
try {
// performing division by zero
int x = a[2] / 0;
}
catch (ArithmeticException e2) {
System.out.println("division by zero is not possible");
}
}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exists");
}
}
// end of main method
}
The keyword throw
 An exception can be caught only if it is identified. Exception can be thrown
by the java run-time system for the code that has been written.
 Achieved by using the throw statement explicitly.
 Syntax
 throw<exception object>
 throw new <exception object>
 E.g
 throw new IndexOutOfBoundsException(“Index out of range”);
Throwing user-defined exceptions
 Throwable has two subclasses
 Exception and error
 User defined should be the sub-classes of exception
 User- defined exception can be created as :
 Throwable UserException= new Throwable();
 Or
 Throwable UserException= new Throwable(“This is user exception message”);
Redirecting
public class Divide {
public static void main(String[] args) {
System.out.println("n Program Execution starts heren");
try {
convertAndDivide ( args[0],args[1]);
}
catch(Exception e) {
System.out.println (e.getMessage () +"n");
e.printStackTrace ();
}
System.out.println("n Program Execution Completes here");
}
Redirecting exception using throw
 Recall that the code capable of throwing an exception is kept in the try block
and the exceptions are caught in the catch block. When there is no
appropriate catch block to handle the (checked) exception that was thrown
by an object, the compiler does not compile the program.
 To overcome this, Java allows the programmer to redirect exceptions that
have been raised up the call stack, by using the keyword throws. Thus, an
exception thrown by a method can be handled either in the method itself or
passed to a different method in the call stack.
 To pass exceptions up to the call stack, the method must be declared with a
throws clause.
 All the exceptions thrown by a method can be declared with a single throws
clause; the clause consists of the keyword throws followed by a comma-
separated list of all the exceptions,
Rethrowing an exception
 An exception that is caught in the try block can be thrown once again and can
be handled. The try block just above the rethrow statement will catch the
rethrown object. If there is no try block just above the rethrow statement
then the method containing the rethrow statement handles it. To propagate
an exception, the catch block can choose to rethrow the exception by using
the throw statement. Note that there is no special syntax for rethrowing.
Program illustrates how an exception can be rethrown .

Rethrowing an exception
public class Divide {
public static void main(String[] args) {
int a, b, c;
try {
a = Integer.parselnt (args [0]);
b = Integer.parselnt (args [l]);
try {
c = a/b;
System.out.println ( a + "I" + b + "=" + c);
}
catch (ArithmeticException e) {
System.out.println ("Second Argument Should not be Zero");
System.out.println ("Rethrowing the object again");
throw e;
}
}
{ System.out.println("Arguments passed should be valid Numbers"); }
catch(ArraylndexOutOfBoundsException e)
{ System.out.println(“Pass Proper Arguments"); }
System.out.println("n Program Execution Completes here");
}
}
 Throwable is a class. Though the Throwable class is derived from the java.lang.Object class in
the Java class library, Throwable is the super-class of all classes that handle exceptions.
Advantages of exception handling
mechanism
 The separation of error-handling code from normal code
 A logical grouping of error types
 The ability to propagate errors up the call stack
CHAPTER-6 MULTITHREADING
THREAD
 Can be defined as a process in execution within a program
 Facility to allow multiple activities within a single process
 Referred as lightweight process
 A thread is a series of executed statements
 Each thread has its own program counter, stack and local variables
 A thread is a nested sequence of method calls
 Its shares memory, files and per-process state
 Thread creation in Java
 Thread implementation in java can be achieved in two ways:
 Extending the class thread- java.lang.Thread class
 Implementing the interface -java.lang.Runnable Interface
 Note: The Thread and Runnable are available in the java.lang.* package
1) By extending thread class
 The class should extend Java Thread class.
 The class should override the run() method.
 The functionality that is expected by the Thread to be executed is written in
the run() method.
 void start(): Creates a new thread and makes it runnable.
void run(): The new thread begins its life inside this method.
public class MyThread extends Thread
{ public void run()
{ System.out.println("thread is running...");
}
public static void main(String[] args)
{ MyThread obj = new MyThread();
obj.start(); }
2) By Implementing Runnable interface
 The class should implement the Runnable interface
 The class should implement the run() method in the Runnable interface
 The functionality that is expected by the Thread to be executed is put in the run() method
E.G
public class MyThread implements Runnable
{ public void run()
{ System.out.println("thread is running..");
} public static void main(String[] args)
{ Thread t = new Thread(new MyThread());
t.start(); }
Ending Thread
 A Thread ends due to the following reasons:
 The thread ends when it comes when the run() method finishes its execution.
 When the thread throws an Exception or Error that is not being caught in the
program.
 Java program completes or ends.
 Another thread calls stop() methods.
Stopping thread using join() method
 Syntax
final void join() throws InterruptedException
 A thread can be not alive state due to any one of the following:
 The thread has not yet started
 Stopped by another thread
 Completion of thread itself
 Simple coding for join()
try {
t1.join()
t2.join()
t3.join()
}
catch (interruptedException e)
{
}
Naming a thread
 Thread constructor to set a name to a thread
Void setName(String threadname)
Thread Life –cycle
 Newborn state
 Runnable state
 Running state
 Dead state
 Blocked state
Thread Life –cycle
 New born state -when a thread is called
 Runnable state-ready for execution but is not being executed currently
 Running state-if the thread gets CPU access, it moves into the running state.in running state any
one of the following will occur:
 It dies
 It gets blocked to the I/O for some reason
 It calls sleep()
 It calls wait()
 It calls yield()
 it is preempted by a thread of higher priority
 Its quantum expires
Continued--
 Thread with a higher priority than running thread can preempt the running thread if any of
situation arise:
 If the thread with the higher priority comes out of the sleeping state.
 The I/O completes for a thread with a higher priority waiting for that I/O
 Either notify() or notifyAll() is called on a thread that called wait
 Dead state-two ways
 If its run() method exits
 A stop() method is invoked
 Blocked state- five conditions occurs:
 When sleep() is called
 When suspend() is called
 When wait() is called
 Thread calls an operation
 Thread is waiting for monitor
Manipulating thread
Name of method function
getName() returns name
SetPriority() To set priority
getPriority() Returns thread priority
isAlive() Whether it is running or not
join() Wait for a thread to terminate
run() Entry point for the thread
start() Start a thread by calling its run method
Stop() Terminate the thread abruptly
Manipulating Thread
 sleep()-sleep() method has prototype
 public static void sleep(long millisec) throws InterruptedException;
 public static void sleep(long millisec, int nanosec) throws InterruptedException;
 suspend()  to stop the thread temporarily and resume()to restart
 wait(), notify() and notifyAll()
 Yield()
Thread priorities and Thread Scheduling
 When new thread is created , the new thread has priority equal to the
priority of the creating thread.
 thread class:
 Thread.MIN_PRIORITY 1
 Thread.MAX_PRIORITY 10
 Thread.NORM_PRIORITY 5(default)
 Set prioritycan be set with setPriority method
 Time-slicing Each thread receives a brief
amount of processor time, called quantum, during
which thread can execute.
 The schedulerJava runtime system selects the
highest priority runnable thread.
 Thread will run until one of the following condition
occurs:
 A higher priority thread becomes runnable
 It yields or its run method exists
 Its time slice has expired
Thread Synchronization
 Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
 Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
 Each object is associated with lock
 Monitor refers to a portion of the code in a program – occupied by only one thread at a
time this specific region within a monitor is known as critical section
 Entering the critical section  acquiring the monitor
 Working with the critical section  owning the monitor
 Leaving with the critical section  releasing the monitor
 The maintains a list of all threads waiting to enter the monitor object to execute
synchronized methods
 1.Synchronized methods
If two or more threads modify an object, the methods that carry the
modifications are declared synchronized
Syntax
Modifier synchronized <return_type> <method_name>(parameters)
 2.Synchronized statements
alternative to declaring a method synchronized, Java shows flexibility.
The programmer can declare a part of the codeas synchronized using
synchronized statement.
Syntax:
synchronized<object><statement>
Dead lock
 Occurs on several occasions
 When two or more threads are waiting for two or more locks to be freed or
circumstances in the program are such that the locks will never be freed.
 If two or more threads are waiting for each other to unlock a synchronized block of
code, where each thread relies on another to do the unlocking- situation is called
deadlock
Method_A()
resource
Method_B()
resource
Daemon Thread
 A “daemon” thread is one that is supposed to provide a
general service in the background as long as the program is
running.
 Thus, when all of the non-daemon threads complete, the
program is terminated. Conversely, if there are any non
daemon threads still running, the program doesn’t terminate.
 setDaemon(true);
 IllegalThreadStateExceptionexception
 isDaemon() method
THREAD GROUPS
Hierarchical thread-group structure
System(thread group)
Main(thread
group)
Main(thread)
threadGroup1
Thread 1 Thread 2
threadGroup2
System threads
Thread groups
 Public ThreadGroup(String StringName)
 Public ThreadGroup(ThreadGroup parentThreadGroup,
String StringName)
 The class thread Provide 3 constructors
 Public Thread(ThreadGroup threadGroup, String StringName)
 Public Thread(ThreadGroup threadGroup, Runnable runnableObject)
 Public Thread(ThreadGroup threadGroup, Runnable runnableObject , String
StringName)
 The activeCount() method on ThreadGroup returns the
total number of threads presently active. It includes the
total number of threads active in the parent ThreadGroup
as well as child ThreadGroups. The enumerate() method
returns an array of Thread references of ThreadGroup .
 Syntax of enumerate()
 int enumerate(Thread list[])
 int enumerate(Thread list[], Boolean value)
 If it is trueit will enumerate all the threads within the group and
also descendents of this ThreadGroup.
 If it is falseit will return only threads within this group.
Methods of a thread group
Method name Functions
getThreadGroup() Returns the reference of the ThreadGroup
getMaxPriority() Returns the maximum priority of a ThreadGroup
setMaxPriority() Sets a maximum priority for a ThreadGroup
getName Returns as String the name of the ThreadGroup
getParent Determines the parent of aa thread group
ParentOf(ThreadGroup t) Returns value true if it is the parent of the ThreadGroup,
otherwise it returns false
void setDaemon(boolean daemon)
This method changes the daemon status
of the thread group.
boolean isDestroyed()
This method tests if this thread group has been
destroyed.
void list()
This method prints information about the
thread group to the standard output.
void suspend()
This method is used to suspend all threads in
the thread group.
void resume()
This method is used to resume all threads in
the thread group which was suspended using
suspend() method.
void stop()
This method is used to stop all threads in the
thread group.
String toString()
This method returns a string representation of
the Thread group.
Communication of Threads
 Inter-thread communication is achieved using the wait(), notify() and
notifyAll() methods of the object class. The methods are final methods in the
object class and can be called only from within a synchronized code.
 wait() tells the thread to give up the monitor and move to sleep until some
other thread enters the same monitor and calls notify().
 notify() wakes up the first thread that called wait() on the same object.
 notifyAll()  wakes up the first thread that called wait() on the same object.
The highest priority thread will run fast.
Difference between wait() and sleep()
Wait( ) sleep( )
wait() method releases the lock sleep() method doesn't release the
lock.
is the method of Object class is the method of Thread class
should be notified by notify() or
notifyAll() methods
after the specified amount of time,
sleep is completed.
THANK YOU

Java -Exception handlingunit-iv

  • 1.
  • 2.
    Exception handling  Exceptionhandling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions.  What is an exception?  An exception is an event that may cause abnormal termination of the program during its execution.  An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.  The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user.
  • 3.
    Why an exceptionoccurs?  There can be several reasons that can cause a program to throw exception.  For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc. Exception handler  Is a piece of code used to deal with to exceptions, either to fix the errors or abort execution in a sophisticated way.  In java catch block is used to handle exceptions that are raised during program execution. Exception Handling  If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. For example look at the system generated exception below:
  • 4.
    Types of exceptions Thereare two types of exceptions in Java: 1)Checked exceptions 2)Unchecked exceptions Checked exceptions All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error . For example, SQLException, IOException, ClassNotFoundException etc.
  • 5.
    Unchecked Exceptions  RuntimeExceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time  so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer  to handle these exceptions and provide a safe exit.  For example, • ArithmeticException, • NullPointerException, • ArrayIndexOutOfBoundsException etc.
  • 6.
    Advantage of exceptionhandling  Exception handling ensures that the flow of the program doesn’t break when an exception occurs. Difference between error and exception  Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.  Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions.
  • 7.
    Constructors and methodsin throwable class Constructors There are four constructors in the Throwable class:  • Throwable ()  • Throwable (String message)  • Throwable (String message, Throwable cause)  • Throwable (Throwable cause) The first two allow constructing an exception object with or without a String message encapsulated in the object.
  • 8.
    Methods  There areseveral methods in the Throwable class. Three useful methods of the Throwable class that provide information about an exception are the following:  • getMessage (): Returns the message that was encapsulated when the object was initiated. It returns null, if there is no message.  • toString(): returns a brief description about the exception of throwable object.  • printStacktrace (): prints the stack trace. StackTrace is a list of the methods executed in sequence that lead to the exception and it is typically used to show the (unhandled) run-time errors on the screen.
  • 9.
    Methods of throwableclass • fillinStackTrace () • getStackTrace () • printStackTrace () • setStackTrace (Stack TraceElement [] stack Trace) When an exceptional condition occurs within a method, the method may instantiate an exception object and hand it to the run-time system to deal with it. This is called throwing an exception.
  • 10.
    Handling exception injava  try  catch  finally  throw  throws
  • 11.
    Try catch example publicclass JavaExceptionExample{ public static void main(String args[]){ try{ //code that may raise exception int data=100/0; }catch(ArithmeticException e) {System.out.println(e);} //rest code of the program System.out.println("rest of the code..."); } }
  • 12.
    Finally -syntax try { //Statements thatmay cause an exception } catch { //Handling exception } finally { //Statements to be executed }
  • 13.
    Nested try class NestedTry{ // main method public static void main(String args[]) { // Main try block try { // initializing array int a[] = { 1, 2, 3, 4, 5 }; // trying to print element at index 5 System.out.println(a[5]); // try-block2 inside another try block
  • 14.
    try { // performingdivision by zero int x = a[2] / 0; } catch (ArithmeticException e2) { System.out.println("division by zero is not possible"); } } catch (ArrayIndexOutOfBoundsException e1) { System.out.println("ArrayIndexOutOfBoundsException"); System.out.println("Element at such index does not exists"); } } // end of main method }
  • 15.
    The keyword throw An exception can be caught only if it is identified. Exception can be thrown by the java run-time system for the code that has been written.  Achieved by using the throw statement explicitly.  Syntax  throw<exception object>  throw new <exception object>  E.g  throw new IndexOutOfBoundsException(“Index out of range”);
  • 16.
    Throwing user-defined exceptions Throwable has two subclasses  Exception and error  User defined should be the sub-classes of exception  User- defined exception can be created as :  Throwable UserException= new Throwable();  Or  Throwable UserException= new Throwable(“This is user exception message”);
  • 17.
    Redirecting public class Divide{ public static void main(String[] args) { System.out.println("n Program Execution starts heren"); try { convertAndDivide ( args[0],args[1]); } catch(Exception e) { System.out.println (e.getMessage () +"n"); e.printStackTrace (); } System.out.println("n Program Execution Completes here"); }
  • 18.
    Redirecting exception usingthrow  Recall that the code capable of throwing an exception is kept in the try block and the exceptions are caught in the catch block. When there is no appropriate catch block to handle the (checked) exception that was thrown by an object, the compiler does not compile the program.  To overcome this, Java allows the programmer to redirect exceptions that have been raised up the call stack, by using the keyword throws. Thus, an exception thrown by a method can be handled either in the method itself or passed to a different method in the call stack.  To pass exceptions up to the call stack, the method must be declared with a throws clause.  All the exceptions thrown by a method can be declared with a single throws clause; the clause consists of the keyword throws followed by a comma- separated list of all the exceptions,
  • 19.
    Rethrowing an exception An exception that is caught in the try block can be thrown once again and can be handled. The try block just above the rethrow statement will catch the rethrown object. If there is no try block just above the rethrow statement then the method containing the rethrow statement handles it. To propagate an exception, the catch block can choose to rethrow the exception by using the throw statement. Note that there is no special syntax for rethrowing. Program illustrates how an exception can be rethrown . 
  • 20.
    Rethrowing an exception publicclass Divide { public static void main(String[] args) { int a, b, c; try { a = Integer.parselnt (args [0]); b = Integer.parselnt (args [l]); try { c = a/b; System.out.println ( a + "I" + b + "=" + c); }
  • 21.
    catch (ArithmeticException e){ System.out.println ("Second Argument Should not be Zero"); System.out.println ("Rethrowing the object again"); throw e; } } { System.out.println("Arguments passed should be valid Numbers"); } catch(ArraylndexOutOfBoundsException e) { System.out.println(“Pass Proper Arguments"); } System.out.println("n Program Execution Completes here"); } }  Throwable is a class. Though the Throwable class is derived from the java.lang.Object class in the Java class library, Throwable is the super-class of all classes that handle exceptions.
  • 22.
    Advantages of exceptionhandling mechanism  The separation of error-handling code from normal code  A logical grouping of error types  The ability to propagate errors up the call stack
  • 23.
    CHAPTER-6 MULTITHREADING THREAD  Canbe defined as a process in execution within a program  Facility to allow multiple activities within a single process  Referred as lightweight process  A thread is a series of executed statements  Each thread has its own program counter, stack and local variables  A thread is a nested sequence of method calls  Its shares memory, files and per-process state  Thread creation in Java  Thread implementation in java can be achieved in two ways:  Extending the class thread- java.lang.Thread class  Implementing the interface -java.lang.Runnable Interface  Note: The Thread and Runnable are available in the java.lang.* package
  • 24.
    1) By extendingthread class  The class should extend Java Thread class.  The class should override the run() method.  The functionality that is expected by the Thread to be executed is written in the run() method.  void start(): Creates a new thread and makes it runnable. void run(): The new thread begins its life inside this method. public class MyThread extends Thread { public void run() { System.out.println("thread is running..."); } public static void main(String[] args) { MyThread obj = new MyThread(); obj.start(); }
  • 25.
    2) By ImplementingRunnable interface  The class should implement the Runnable interface  The class should implement the run() method in the Runnable interface  The functionality that is expected by the Thread to be executed is put in the run() method E.G public class MyThread implements Runnable { public void run() { System.out.println("thread is running.."); } public static void main(String[] args) { Thread t = new Thread(new MyThread()); t.start(); }
  • 26.
    Ending Thread  AThread ends due to the following reasons:  The thread ends when it comes when the run() method finishes its execution.  When the thread throws an Exception or Error that is not being caught in the program.  Java program completes or ends.  Another thread calls stop() methods.
  • 27.
    Stopping thread usingjoin() method  Syntax final void join() throws InterruptedException  A thread can be not alive state due to any one of the following:  The thread has not yet started  Stopped by another thread  Completion of thread itself  Simple coding for join() try { t1.join() t2.join() t3.join() } catch (interruptedException e) { }
  • 28.
    Naming a thread Thread constructor to set a name to a thread Void setName(String threadname)
  • 29.
    Thread Life –cycle Newborn state  Runnable state  Running state  Dead state  Blocked state
  • 30.
    Thread Life –cycle New born state -when a thread is called  Runnable state-ready for execution but is not being executed currently  Running state-if the thread gets CPU access, it moves into the running state.in running state any one of the following will occur:  It dies  It gets blocked to the I/O for some reason  It calls sleep()  It calls wait()  It calls yield()  it is preempted by a thread of higher priority  Its quantum expires
  • 31.
    Continued--  Thread witha higher priority than running thread can preempt the running thread if any of situation arise:  If the thread with the higher priority comes out of the sleeping state.  The I/O completes for a thread with a higher priority waiting for that I/O  Either notify() or notifyAll() is called on a thread that called wait  Dead state-two ways  If its run() method exits  A stop() method is invoked  Blocked state- five conditions occurs:  When sleep() is called  When suspend() is called  When wait() is called  Thread calls an operation  Thread is waiting for monitor
  • 32.
    Manipulating thread Name ofmethod function getName() returns name SetPriority() To set priority getPriority() Returns thread priority isAlive() Whether it is running or not join() Wait for a thread to terminate run() Entry point for the thread start() Start a thread by calling its run method Stop() Terminate the thread abruptly
  • 33.
    Manipulating Thread  sleep()-sleep()method has prototype  public static void sleep(long millisec) throws InterruptedException;  public static void sleep(long millisec, int nanosec) throws InterruptedException;  suspend()  to stop the thread temporarily and resume()to restart  wait(), notify() and notifyAll()  Yield()
  • 34.
    Thread priorities andThread Scheduling  When new thread is created , the new thread has priority equal to the priority of the creating thread.  thread class:  Thread.MIN_PRIORITY 1  Thread.MAX_PRIORITY 10  Thread.NORM_PRIORITY 5(default)
  • 35.
     Set prioritycanbe set with setPriority method  Time-slicing Each thread receives a brief amount of processor time, called quantum, during which thread can execute.  The schedulerJava runtime system selects the highest priority runnable thread.  Thread will run until one of the following condition occurs:  A higher priority thread becomes runnable  It yields or its run method exists  Its time slice has expired
  • 36.
    Thread Synchronization  Synchronizationin java is the capability to control the access of multiple threads to any shared resource.  Java Synchronization is better option where we want to allow only one thread to access the shared resource.  Each object is associated with lock  Monitor refers to a portion of the code in a program – occupied by only one thread at a time this specific region within a monitor is known as critical section  Entering the critical section  acquiring the monitor  Working with the critical section  owning the monitor  Leaving with the critical section  releasing the monitor
  • 37.
     The maintainsa list of all threads waiting to enter the monitor object to execute synchronized methods  1.Synchronized methods If two or more threads modify an object, the methods that carry the modifications are declared synchronized Syntax Modifier synchronized <return_type> <method_name>(parameters)  2.Synchronized statements alternative to declaring a method synchronized, Java shows flexibility. The programmer can declare a part of the codeas synchronized using synchronized statement. Syntax: synchronized<object><statement>
  • 38.
    Dead lock  Occurson several occasions  When two or more threads are waiting for two or more locks to be freed or circumstances in the program are such that the locks will never be freed.  If two or more threads are waiting for each other to unlock a synchronized block of code, where each thread relies on another to do the unlocking- situation is called deadlock Method_A() resource Method_B() resource
  • 39.
    Daemon Thread  A“daemon” thread is one that is supposed to provide a general service in the background as long as the program is running.  Thus, when all of the non-daemon threads complete, the program is terminated. Conversely, if there are any non daemon threads still running, the program doesn’t terminate.  setDaemon(true);  IllegalThreadStateExceptionexception  isDaemon() method
  • 40.
    THREAD GROUPS Hierarchical thread-groupstructure System(thread group) Main(thread group) Main(thread) threadGroup1 Thread 1 Thread 2 threadGroup2 System threads
  • 41.
    Thread groups  PublicThreadGroup(String StringName)  Public ThreadGroup(ThreadGroup parentThreadGroup, String StringName)  The class thread Provide 3 constructors  Public Thread(ThreadGroup threadGroup, String StringName)  Public Thread(ThreadGroup threadGroup, Runnable runnableObject)  Public Thread(ThreadGroup threadGroup, Runnable runnableObject , String StringName)
  • 42.
     The activeCount()method on ThreadGroup returns the total number of threads presently active. It includes the total number of threads active in the parent ThreadGroup as well as child ThreadGroups. The enumerate() method returns an array of Thread references of ThreadGroup .  Syntax of enumerate()  int enumerate(Thread list[])  int enumerate(Thread list[], Boolean value)  If it is trueit will enumerate all the threads within the group and also descendents of this ThreadGroup.  If it is falseit will return only threads within this group.
  • 43.
    Methods of athread group Method name Functions getThreadGroup() Returns the reference of the ThreadGroup getMaxPriority() Returns the maximum priority of a ThreadGroup setMaxPriority() Sets a maximum priority for a ThreadGroup getName Returns as String the name of the ThreadGroup getParent Determines the parent of aa thread group ParentOf(ThreadGroup t) Returns value true if it is the parent of the ThreadGroup, otherwise it returns false
  • 44.
    void setDaemon(boolean daemon) Thismethod changes the daemon status of the thread group. boolean isDestroyed() This method tests if this thread group has been destroyed. void list() This method prints information about the thread group to the standard output. void suspend() This method is used to suspend all threads in the thread group. void resume() This method is used to resume all threads in the thread group which was suspended using suspend() method. void stop() This method is used to stop all threads in the thread group. String toString() This method returns a string representation of the Thread group.
  • 45.
    Communication of Threads Inter-thread communication is achieved using the wait(), notify() and notifyAll() methods of the object class. The methods are final methods in the object class and can be called only from within a synchronized code.  wait() tells the thread to give up the monitor and move to sleep until some other thread enters the same monitor and calls notify().  notify() wakes up the first thread that called wait() on the same object.  notifyAll()  wakes up the first thread that called wait() on the same object. The highest priority thread will run fast.
  • 46.
    Difference between wait()and sleep() Wait( ) sleep( ) wait() method releases the lock sleep() method doesn't release the lock. is the method of Object class is the method of Thread class should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.
  • 47.