0% found this document useful (0 votes)
34 views40 pages

Java Exception Handling & Multithreading Guide

This document covers exception handling and multithreading in Java, detailing exception hierarchy, multiple catch clauses, nested try statements, and the use of the finally block. It explains built-in and user-defined exceptions, as well as the life cycle of threads and their various states. Additionally, it provides examples of creating threads using both the Thread class and the Runnable interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views40 pages

Java Exception Handling & Multithreading Guide

This document covers exception handling and multithreading in Java, detailing exception hierarchy, multiple catch clauses, nested try statements, and the use of the finally block. It explains built-in and user-defined exceptions, as well as the life cycle of threads and their various states. Additionally, it provides examples of creating threads using both the Thread class and the Runnable interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING

UNIT III EXCEPTION HANDLING AND MULTITHREADING


Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in Exceptions –
User defined Exception. Multithreaded Programming: Java Thread Model–Creating a Thread and Multiple
Threads – Priorities – Synchronization – Inter Thread Communication- Suspending –Resuming, and
Stopping Threads – Multithreading. Wrappers – Auto boxing.

1. Explain about exception hierarchy.


An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out
of memory.
 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.
 Exceptions can be generated by the Java run-time system, or they 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.
 Java exception handling is managed via five keywords:
try, catch, throw, throws, finally.
 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.
 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.

EXCEPTION HIERARCHY :

 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. This is also the class that you will subclass to create your own custom
exception types. There is an important subclass of Exception, called 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. 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.

USING TRY AND CATCH:


Although the default exception handler provided by the Java run-time system is useful for
debugging, you will usually want to handle an exception yourself.
Exception handler provides two benefits.
1) It allows you to fix the error.
2) It prevents the program from automatically terminating.
Program:
class Exc2
{
public static void main(String args[])
{
int d, a; try
{
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
}
catch (ArithmeticException e)
{
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}}

This program generates the following output:


Division by zero.
After catch statement.

2. Explain about multiple catch clauses.


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.

class MultipleCatches
{
public static void main(String args[])
{
try
{ int a = 0; [Link]("a = " + a); int b = 42 / a;
int c[] = { 1 }; c[42] = 99;
}
catch(ArithmeticException e)
{
[Link]("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}}

Output:
a=0
Divide by 0: [Link]: / by zero After try/catch blocks.

3. Explain about nested try statements.


The try statement can be nested. That is, a try statement can be inside the block 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. Here is an example that uses nested try statements:

An example of nested try statements.


class NestTry
{
public static void main(String args[])
{
try {
int a = 0;
int b = 42 / a; [Link]("a = " + a); try
{
if(a==1)
a = a/(a-a); if(a==2)
{
int c[] = { 1 }; c[42] = 99;
}}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index out-of-bounds: " + e);
}}
catch(ArithmeticException e)
{
[Link]("Divide by 0: " + e);}}}

This program nests one try block within another. The program works as follows. When you execute
the program with no command-line arguments, a divide-by-zero exception is generated by the outer try
block. Execution of the program with one command-line argument generates a divide-by-zero exception
from within the nested try block. Since the inner block does not catch this exception, it is passed on to the
outer try block, where it is handled. If you execute the program with two command-line arguments, an
array boundary exception is generated from within the inner try block.

Output:
Divide by 0: [Link]: / by zero
Output when a=1:
a=1
Divide by 0: [Link]: / by zero C:\>java NestTry One Two
Output when a=2:
Array index out-of-bounds: [Link]
finally:
When exceptions are thrown, execution in a method takes a rather abrupt, 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.
Finally creates a block of code that will be executed after a try /catch block 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.
7. Explain in detail about various types of exception.
An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.

Two types of exceptions are


 Built in exception
 User defined exception
1) BUILT-IN EXCEPTIONS:
Inside the standard package [Link], Java defines several exception classes. The most general of
exceptions are the subclasses of the standard type RuntimeException. These exceptions need
not be included in any method's throws list.
• Checked Exception
Checked exceptions are checked at compile-time. The classes which directly inherit Throwable
class except RuntimeException and Error are known as checked exceptions.
e.g. IOException, SQLException etc. Checked exceptions are checked at compile- time.

• Unchecked Exception
Unchecked exceptions are not checked at compile-time, but they are checked at runtime. The
classes which inherit RuntimeException are known as unchecked exceptions. These exceptions need not be
included in any method's throws list.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Program:
class MultipleCatches
{
public static void main(String args[])
{
try
{
int a = 0;
[Link]("a = " + a); int b = 42 / a;
int c[] = { 1 }; c[42] = 99;
}
catch(ArithmeticException e)
{
[Link]("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}
finally
{
[Link](" Finally block");
}}
Output:
C:\>java MultipleCatches a = 0
Divide by 0: [Link]: / by zero After try/catch blocks.
Finally block

2) USER DEFINED EXCEPTION:


User can create their own exception types to handle situations specific to user applications. This is
quite easy to do: just define a subclass of Exception .
The Exception class does not define any methods of its own. It inherits the methods provided by
Throwable. Thus, all exceptions, including those that you create, have the methods defined by Throwable
available to them.
Exception defines four constructors. Two support chained exceptions. The other two are shown
here:
Exception( ) Exception(String msg)
The first form creates an exception that has no description. The second form lets you specify a
description of the exception.

Program:
class MyException extends Exception
{
int detail; MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException:" + detail ;
}
}
class ExceptionDemo
{
static void compute(int a) throws MyException
{
[Link]("Called compute”); if(a > 10)
throw new MyException(a); [Link]("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1); compute(20);
}
catch (MyException e)
{
[Link]("Caught " + e);
}}}
Output:
Called compute(1) Normal exit Called compute(20)
Caught MyException[20]

8. Discuss the life cycle of threads with neat diagram.


1) Thread is the smallest unit 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.
2) Threads are lighter weight. They share the same address space and cooperatively share the same
heavyweight process. Interthread communication is inexpensive, and context switching from one
thread to the next is lower in cost.
3) Multithreading enables to write efficient programs that make maximum use of the processing
power available in the system. Multithreading keep the idle time to a minimum.
Threads exist in several states.
• A thread can be running. It can be ready to run as soon as it gets CPU time.
• A running thread can be 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.

Obtaining A Thread’s State


A thread can exist in a number of different states. You can obtain the current state of a thread by
calling the getState( ) method defined by Thread. It is shown here:
[Link] getState( )
It returns a value of type [Link] that indicates the state of the thread at the time at which the
call was made. State is an enumeration defined by Thread. Here are the values that can be returned by
getState( ):

Value State
BLOCKED A thread that has suspended execution because it is waiting
to acquire a lock.
NEW A thread that has not begun execution.
RUNNABLE A thread that either is currently executing or will execute
when it gains access to the CPU.
TERMINATED A thread that has completed execution.
A thread that has suspended execution for a specified
TIMED_WAITING period of time, such as when it has called sleep( ). This
state is also entered when a timeout version of wait( ) or
join( ) is called.
A thread that has suspended execution because it is waiting
WAITING for some action to occur. For example, it is waiting because
of a call to a non-timeout version of wait( ) or join( ).

Given a Thread instance, you can use getState( ) to obtain the state of a thread. For example, the
following sequence determines if a thread called thrd is in the RUNNABLE state at the time getState( ) is
called:
[Link] ts = [Link]();
if(ts == [Link]) // ...
It is important to understand that a thread’s state may change after the call to getState( ). Thus,
depending on the circumstances, the state obtained by calling getState( ) may not reflect the actual state of
the thread only a moment later. For this (and other) reasons, getState( ) is not intended to provide a means
of synchronizing threads. It’s primarily used for debugging or for profiling a thread’s run-time
characteristics.

9. Develop a program for creating threads by using Thread class and Runnable interface.
(or) Why do we need both start() and run() method both? can we achieve it with only run() method?
We can call run() method if we want but then it would behave just like a normal method and we
would not be able to take the advantage of multithreading. When the run method gets called though start()
method then a new separate thread is being allocated to the execution of run method, so if more than one
thread calls start() method that means their run method is being executed by separate threads (these threads
run simultaneously).
Java defines two ways in which this can be accomplished:
1) By extending the Thread class.
2) By implement the Runnable interface.
1. Creating thread by using Thread class:
Create a new class that extends Thread, and then 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.

class multithreading extends Thread


{
public void run()
{
try
{
[Link] ("Thread " + [Link]().getId() + " is running");
}
catch (Exception e)
{
[Link] ("Exception is caught");
}}}
public class multithreadingdemo
{
public static void main(String[] args)
{
multithreading m1=new multithreading(); multithreading m2=new multithreading(); [Link]();
[Link]();
}}
Output:
Thread 21 is running Thread 22 is running

2. Creating thread by using Runnable interface:


The easiest way to create a thread is to create a class that implements the Runnable interface. 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. It is important to understand that
run( ) can call other methods, use other 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. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb)
Thread(Runnable threadOb, String threadName) Thread(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( )
Here is an example that creates a new thread and starts it running:

class multithreading implements Runnable


{
public void run()
{
try
{
[Link] ("Thread " + [Link]().getId() + " is running");
}
catch (Exception e)
{
[Link] ("Exception is caught");
}}}
public class multithreadingdemo
{
public static void main(String[] args)
{
multithreading m1=new multithreading(); Thread t1 = new Thread(m1);
multithreading m2=new multithreading(); Thread t2 = new Thread(m2);
[Link]();
[Link]();
}}

Output:
Thread 21 is running Thread 22 is running

10. Develop a java program that provide synchronization for two threads deposit and withdraw in
a bank application.
(or) What is thread synchronization? Discuss with an example.
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. Java provides unique, language-level support for it.
The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem. Synchronization can be done in two ways:
1) Using Synchronized Methods
2) Using synchronized Statement or synchronized block

1)Using Synchronized Methods:


Synchronization is easy in Java, because all objects have their own implicit monitor associated with
them. To enter an object’s monitor, just call a method that has been modified with the synchronized
keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other
synchronized method) on the same instance have to wait. To exit the monitor and
relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the
synchronized method.

Program:
class bank{
int amount=5000;
synchronized void transaction(int n,char c ){ try
{
if (c=='d')
{
[Link]("Before deposit Balance ="+amount); amount =amount+n;
[Link]("After deposit Balance ="+amount);
}
else if(c=='w') {
[Link]("Before withdraw Balance ="+amount);
amount = amount-n;
[Link]("After withdraw Balance ="+amount);
}
[Link](400);
}
catch(Exception e)
{
[Link](e);}
}}
class deposit extends Thread
{
bank t; deposit(bank x){ t=x;
}
public void run(){ [Link](4000,'d');
}}
class withdraw extends Thread{ bank t;
withdraw(bank x){ t=x;
}
public void run(){ [Link](2000,'w');
}}
public class testsync{
public static void main(String args[]){
bank obj = new bank(); deposit t1=new deposit(obj);
withdraw t2=new withdraw(obj); [Link]();
[Link]();
}}

Output:
Before deposit Balance =5000
After deposit Balance =9000
Before withdraw Balance =9000
After withdraw Balance =7000
2) The synchronized Statement: (synchronized block)

While creating synchronized methods within classes that you create is an easy and effective means
of achieving synchronization, it will not work in all cases. To understand why, consider the following.
Imagine that you want to synchronize access to objects of a class that was not designed for multithreaded
access. That is, the class does not use synchronized methods.
Further, this class was not created by you, but by a third party, and you do not have access to the
source code. Thus, you can’t add synchronized to the appropriate methods within the class. How can
access to an object of this class be synchronized? Fortunately, the solution to this problem is quite easy:
You simply put calls to the methods defined by this class inside a synchronized block.
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. 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 monitor.

Program:
class bank{
int amount=5000;
void transaction(int n,char c ){
try
{
if (c=='d')
{
[Link]("Before deposit Balance ="+amount); amount =amount+n;
[Link]("After deposit Balance ="+amount);
}
else if(c=='w') {
[Link]("Before withdraw Balance ="+amount); amount = amount-n;
[Link]("After withdraw Balance ="+amount);
}
[Link](400);
}
catch(Exception e){[Link](e);}
}
}

class deposit extends Thread{ bank t;


deposit(bank x){ t=x;
}
public void run(){ synchronized(t)
{
[Link](4000,'d');
}}}
class withdraw extends Thread{ bank t;
withdraw(bank x){ t=x;
}
public void run(){ synchronized(t){ [Link](2000,'w');
}}}

public class testsync{


public static void main(String args[]){ bank obj = new bank();
deposit t1=new deposit(obj); withdraw t2=new withdraw(obj); [Link]();
[Link]();
}
}
Output:
Before deposit Balance =5000
After deposit Balance =9000
Before withdraw Balance =9000
After withdraw Balance =7000

11. Write a java program for inventory problem to illustrate the usage of thread synchronized
keyword and interthread communication process. They have three classes called consumer,
producer and stock.
(Or) Explain about interthread communication with example program.
 Java includes an elegant interprocess communication mechanism via the wait( ), notify(
), and notifyAll( ) methods. Inter-thread communication is all about allowing synchronized
threads to communicate with each other. 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.
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will
be granted access.

Consider the following sample program that implements a simple form of the producer/ consumer
problem. It consists of four classes: Queue, the queue that you’re trying to synchronize; Producer, the
threaded object that is producing queue entries; Consumer, the threaded object that is consuming queue
entries; and PC, the tiny class that creates the single Q, Producer, and Consumer.

class Queue
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet) try {
wait();
}
catch(InterruptedException e)
{
[Link]("InterruptedException caught");
}
[Link]("Got: " + n); valueSet = false;
notify();
return n;
}

synchronized void put(int x)


{
while(valueSet) try {
wait();
}
catch(InterruptedException e)
{
[Link]("InterruptedException caught");
}
n = x;
valueSet = true; [Link]("Put: " + n); notify();
}}

class Producer extends Thread { Queue q;


Producer(Queue q1) { q = q1;
}
public void run() { int i = 0; while(true) { [Link](i++);
}}}

class Consumer extends Thread{ Queue q;


Consumer(Queue q1) { q = q1;
}

public void run() { while(true) { [Link]();


}}}

public class PCFixed


{
public static void main(String args[])
{
Queue q = new Queue(); Producer p=new Producer(q); Consumer c= new Consumer(q); [Link]();
[Link]();
[Link]("Press Control-C to stop.");
}}
Output:
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5

12. Explain about creating multiple threads and thread priorities.


The program can create as many threads as it needs. class multithreading extends Thread
{
public void run()
{
try
{
[Link] ("Thread " + [Link]().getId() + " is running");
}
catch (Exception e)
{
[Link] ("Exception is caught");
}}}
public class multithreadingdemo
{
public static void main(String[] args)
{
multithreading m1=new multithreading(); multithreading m2=new multithreading();
[Link]();
[Link]();
}}

Output:
Thread 21 is running Thread 22 is running

Using isAlive( ) and join( )


Often you will want the main thread to finish last. This can be 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.
Two ways exist to determine whether a thread has finished.
1) 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. isAlive( ) is occasionally useful.
2) Most commonly used method to wait for a thread to finish is called join( ), shown here:
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates. 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.

class jointhread extends Thread{ public void run() {


try {
[Link]([Link]().getName()); [Link](100);
}
catch (InterruptedException e) { [Link]("Thread interrupted");
}}}
public class JoinExample {
public static void main(String[] args) {
jointhread t1 = new jointhread();
jointhread t2 = new jointhread();
[Link]();
[Link]();
[Link]("t1 Alive - " + [Link]()); [Link]("t2 Alive - " + [Link]());
try {
[Link]();
[Link]();
}

catch (InterruptedException e) { [Link]("Thread interrupted");


}
[Link]("t1 Alive - " + [Link]()); [Link]("t2 Alive - " + [Link]());
[Link]("Processing finished");
}}
Output:
Thread-0 Thread-1
t1 Alive - true t2 Alive - true t1 Alive - false t2 Alive - false
Processing finished

THREAD PRIORITIES:
 Thread priorities are used by the thread scheduler to decide when each thread should be allowed
to run. In theory, 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. (For example,
how an operating system implements multitasking can affect the relative availability of CPU time.)
 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 (from sleeping or waiting on I/O, for
example), it will preempt the lower-priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.

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

13. Explain about deadlock .


• Deadlock 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.
However, if the thread in Y, in turn, tries to call any synchronized method 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:

1) In general, it occurs only rarely, when the two threads time-slice in just the right way.
2) It may involve more than two threads and two synchronized objects.

// Online Java Compiler


// Use this editor to write, compile and run your Java code online
public class TestThread
{
static String r1 = "java"; static String r2 = "program";

public static void main(String args[]) {


ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
[Link]();
[Link]();
}
static class ThreadDemo1 extends Thread
{
public void run()
{
synchronized (r1)
{
[Link]("Thread 1: Holding lock 1...");
[Link]("Thread 1: Waiting for lock 2...");
synchronized (r2)
{
[Link]("Thread 1: Holding lock 1 & 2...");
}}}}
static class ThreadDemo2 extends Thread
{
public void run()
{
synchronized (r2)
{
[Link]("Thread 2: Holding lock 2...");
[Link]("Thread 2: Waiting for lock 1...");
synchronized (r1)
{
[Link]("Thread 2: Holding lock 1 & 2...");
}
}
}
}}
Output
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...
As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of
the first conditions that you should check for.

[Link] about suspending, resuming, and stopping threads.


 stop() method in Thread – This method terminates the thread execution.
 suspend() method in Thread – If you want to stop the thread execution and start it again
when a certain event occurs. ...
 resume() method in Thread – resume() method works with suspend() method.

 The mechanisms to suspend, stop, and resume threads differ between early versions of Java,
such as Java 1.0, and more modern versions, beginning with Java 2. Prior to Java 2, a program used
suspend( ), resume( ), and stop( ), which are methods defined by Thread, to pause, restart, and stop
the execution of a thread. Although these methods seem to be a perfectly reasonable and convenient
approach to managing the execution of threads, they must not be used for new Java programs.

 Here’s why. The suspend( ) method of the Thread class was deprecated by Java 2 several years
ago. This was done because suspend( ) can sometimes cause serious system failures. Assume that a
thread as obtained locks on critical data structures. If that thread is suspended at that point, those locks
are not relinquished. Other threads that may be waiting for those resources can be deadlocked.
 The resume( ) method is also deprecated. It does not cause problems, but cannot be used
without the suspend( ) method as its counterpart. The stop( ) method of the Thread class, too, was
deprecated by Java 2. This was done because this method can sometimes cause serious system failures.
 Assume that a thread is writing to a critically important data structure and has completed only
part of its changes. If that thread is stopped at that point, that data structure might be left in a corrupted
state. The trouble is that stop( ) causes any lock the calling thread holds to be released. Thus, the
corrupted data might be used by another thread that is waiting on the same lock.
 Because you can’t now use the suspend( ), resume( ), or stop( ) methods to control a thread,
you might be thinking that no way exists to pause, restart, or terminate a thread.
 But, fortunately, this is not true. Instead, a thread must be designed so that the run( ) method
periodically checks to determine whether that thread should suspend, resume, or stop its own
execution. This is accomplished by establishing a flag variable that indicates the execution state of the
thread. As long as this flag is set to “running,” the run( ) method must continue to let the thread
execute. If this variable is set to “suspend,” the thread must pause. If it is set to “stop,” the thread must
terminate. Of course, a variety of ways exist in which to write such code, but the central theme will be
the same for all programs.
 The following example illustrates how the wait( ) and notify( ) methods that are inherited from
Object can be used to control the execution of a thread. Let us consider its operation. The NewThread
class contains a boolean instance variable named suspendFlag, which is used to control the execution
of the thread. It is initialized to false by the constructor. The run( ) method contains a synchronized
statement block that checks suspendFlag. If that variable is true, the wait( ) method is invoked to
suspend the execution of the thread. The mysuspend( ) method sets suspendFlag to true. The
myresume( ) method sets suspendFlag to false and invokes notify( ) to wake up the thread. Finally,
the main( ) method has been modified to invoke the mysuspend( ) and myresume( ) methods.

class NewThread implements Runnable


{
String name; Thread t;
boolean suspendFlag; NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
[Link]("New thread: " + t);
suspendFlag = false;
[Link]();
}
public void run()
{
try
{
for(int i = 3; i > 0; i--)
{
[Link](name + ": " + i);
[Link](200);
synchronized(this)
{
while(suspendFlag)
{
wait();
}}}}
catch (InterruptedException e)
{
[Link](name + " interrupted.");
}
[Link](name + " exiting.");
}
void mysuspend()
{
suspendFlag = true;
}
synchronized void myresume()
{
suspendFlag = false; notify();
}}
class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try
{
[Link](1000);
[Link]();
[Link]("Suspending thread One");
[Link](1000);
[Link]();
[Link]("Resuming thread One");
[Link]();
[Link]("Suspending thread Two");
[Link](1000);
[Link]();
[Link]("Resuming thread Two");
}
catch (InterruptedException e)
{
[Link]("Main thread Interrupted");
}
// wait for threads to finish try
{
[Link]("Waiting for threads to finish.");
[Link]();
[Link]();
}
catch (InterruptedException e)
{
[Link]("Main thread Interrupted");
}
[Link]("Main thread exiting.");
}}

Output:
New thread: Thread[One,5,main] New thread: Thread[Two,5,main] One: 3
Two: 3
One: 2
Two: 2
One: 1Two: 1 One exiting. Two exiting.
Suspending thread One Resuming thread One Suspending thread Two Resuming thread Two
Waiting for threads to finish. Main thread exiting.

[Link] about type wrappers in java.


Java uses primitive types (also called simple types), such as int or double, to hold the basic data
types supported by the language. Primitive types, rather than objects, are used for these quantities for the
sake of performance. Using objects for these values would add an unacceptable overhead to even the
simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and they do not
inherit Object.
Despite the performance benefit offered by the primitive types, there are times when you will need
an object representation. For example, you can’t pass a primitive type by reference to a method. Also,
many of the standard data structures implemented by Java operate on objects, which means that you can’t
use these data structures to store primitive types. To handle these situations, Java provides type wrappers,
which are classes that encapsulate a primitive type within an object.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These
classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object
hierarchy.
Character:
Character is a wrapper around a char. The constructor for Character is Character(char ch) Here,
ch specifies the character that will be wrapped by the Character object being created.
To obtain the char value contained in a Character object, call charValue( ), shown here:
char charValue( )
It returns the encapsulated character.
Boolean
Boolean is a wrapper around boolean values. It defines these constructors:
Boolean(boolean boolValue) Boolean(String boolString)
In the first version, boolValue must be either true or false. In the second version, if boolString
contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise,
it will be false. To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue( )
It returns the boolean equivalent of the invoking object.

The Numeric Type Wrappers


By far, the most commonly used type wrappers are those that represent numeric values. These are
Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers inherit the abstract class
Number. Number declares methods that return the value of an object in each of the different number
formats. These methods are shown here:

byte byteValue( ) double doubleValue( ) float floatValue( )


int intValue( ) long longValue( )
short shortValue( )
For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns the
value as a float, and so on. These methods are implemented by each of the numeric type wrappers.
All of the numeric type wrappers define constructors that allow an object to be constructed from a
given value, or a string representation of that value. For example, here are the constructors defined for
Integer:
Integer(int num) Integer(String str)
If str does not contain a valid numeric value, then a NumberFormatException is thrown. All of
the type wrappers override toString( ). It returns the human-readable form of the value contained within
the wrapper. This allows you to output the value by passing a type wrapper object to println( ), for
example, without having to convert it into its primitive [Link] following program demonstrates how to
use a numeric type wrapper to encapsulate a value and then extract that value.

// Demonstrate a type wrapper. class Wrap {


public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = [Link]();
[Link](i + " " + iOb); // displays 100 100
}}
This program wraps the integer value 100 inside an Integer object called iOb. The program then
obtains this value by calling intValue( ) and stores the result in i.
The process of encapsulating a value within an object is called boxing. Thus, in the program, this line
boxes the value 100 into an Integer:
Integer iOb = new Integer(100);
The process of extracting a value from a type wrapper is called unboxing. For example, the program
unboxes the value in iOb with this statement:
int i = [Link]();
The same general procedure used by the preceding program to box and unbox values has been
employed since the original version of Java. However, with the release of JDK 5, Java
fundamentally improved on this through the addition of autoboxing, described next.

[Link] about autoboxing and unboxing.


Beginning with JDK 5, Java added two important features:
autoboxing and auto-unboxing.
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its
equivalent type wrapper whenever an object of that type is needed. There is no need to explicitly construct
an object.
Auto-unboxing is the process by which the value of a boxed object is automatically extracted
(unboxed) from a type wrapper when its value is needed. There is no need to call a method such as
intValue( ) or doubleValue( ).
The addition of autoboxing and auto-unboxing greatly streamlines the coding of several algorithms,
removing the tedium of manually boxing and unboxing values. It also helps prevent errors. Moreover, it is
very important to generics, which operates only on objects. Finally, autoboxing makes working with the
Collections Framework much easier.
With autoboxing it is no longer necessary to manually construct an object in order to wrap a
primitive type. You need only assign that value to a type-wrapper reference. Java automatically constructs
the object for you. For example, here is the modern way to construct an Integer object that has the value
100:
Integer iOb = 100; // autobox an int
Notice that no object is explicitly created through the use of new. Java handles this for you,
automatically.
To unbox an object, simply assign that object reference to a primitive-type variable. For example, to
unbox iOb, you can use this line:
int i = iOb; // auto-unbox
Java handles the details for you.
Here is the preceding program rewritten to use autoboxing/unboxing:
// Demonstrate autoboxing/unboxing.
class AutoBox
{
public static void main(String args[])
{
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
[Link](i + " " + iOb); // displays 100 100
}}
Autoboxing/Unboxing Boolean and Character Values
Java also supplies wrappers for boolean and char. These are Boolean and Character.
Autoboxing/unboxing applies to these wrappers, too. For example, consider the following program:
// Autoboxing/unboxing a Boolean and Character.
class AutoBox5
{
public static void main(String args[])
{
Boolean b = true; if(b)
[Link]("b is true");
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
[Link]("ch2 is " + ch2);
}}

The output is shown here:


b is true
ch2 is x

Part-A
1. What is an exception?
Exception is an abnormal condition which occurs during the execution of a program and disrupts
normal flow of the program. This exception must be handled properly. If it is not handled, program will be
terminated abruptly.
2. How the exceptions are handled in java? OR Explain exception handling mechanism in java?
Exceptions in java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception are kept in this block.
catch block : This block catches the exceptions occurred in the try block.
finally block : This block is always executed whether exception is occurred in the try block or not and
occurred exception is caught in the catch block or not.

3. What is the difference between error and exception in java?


Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused by
the application itself. For example, NullPointerException occurs when an application tries to access null
object.

4. Can we write only try block without catch and finally blocks?
No, It shows compilation error. The try block must be followed by either catch or finally block.
You can remove either catch block or finally block but not both.

5. What is unreachable catch block error?


When you are keeping multiple catch blocks, the order of catch blocks must be from most specific
to most general ones. i.e sub classes of Exception must come first and super classes later. If you keep super
classes first and sub classes later, compiler will show unreachable catch block error.

6. Describe the hierarchy of exceptions in java?


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. This is also the class that you will subclass to create your own custom exception types. There
is an important subclass of Exception, called 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. 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.

7. What are run time exceptions in java. Give example?


The exceptions which occur at run time are called as run time exceptions. These exceptions are
unknown to compiler. All sub classes of [Link] and [Link] are run time
exceptions. These exceptions are unchecked type of exceptions. For example, NumberFormatException,
NullPointerException, ClassCastException,

8. What are checked and unchecked exceptions in java?


Checked exceptions are the exceptions which are known to compiler. These exceptions are checked
at compile time only. Hence the name checked exceptions. These exceptions are also called compile time
exceptions. Because, these exceptions will be known during compile time.
Unchecked exceptions are those exceptions which are not at all known to compiler. These
exceptions occur only at run time. These exceptions are also called as run time exceptions. All sub classes
of [Link] and [Link] are unchecked exceptions.

9. What is Re-throwing an exception in java?


Exceptions raised in the try block are handled in the catch block. If it is unable to handle that
exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.

10. What is the use of throws keyword in java?


If a method is capable of causing an exception that it does not handle, it 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.

11. What is the difference between final, finally and finalize in java?
final keyword :
final is a keyword which is used to make a variable or a method or a class as “unchangeable“.
finally Block :
finally is a block which is used for exception handling along with try and catch blocks. finally block
is always executed whether exception is raised or not and raised exception is handled or not. Most of time,
this block is used to close the resources like database connection, I/O resources etc.
finalize() Method :
finalize() method is a protected method of [Link] class. It is inherited to every class you
create in java. This method is called by garbage collector thread before an object is removed from the
memory. finalize() method is used to perform some clean up operations on an object before it is removed
from the memory.

12. How do you create customized exceptions in java?


In java, we can define our own exception classes as per our requirements. These exceptions are
called user defined exceptions in java OR Customized exceptions. User defined exceptions must extend
any one of the classes in the hierarchy of exceptions.

13. What is the difference between throw, throws and throwable in java?
throw In Java :
throw is a keyword in java which is used to throw an exception manually. Using throw keyword,
you can throw an exception from any method or block. But, that exception must be of type
[Link] class or it’s sub classes. Below example shows how to throw an exception using throw
keyword.
throws In Java :
throws is also a keyword in java which is used in the method signature to indicate that this method
may throw mentioned exceptions. The caller to such methods must handle the mentioned exceptions either
using try-catch blocks or using throws keyword. Below is the syntax for using throws keyword.
Throwable In Java :
Throwable is a super class for all types of errors and exceptions in java. This class is a member of
[Link]. Only instances of this class or it’s sub classes are thrown by the java virtual machine or
by the throw statement. The only argument of catch block must be of this type or it’s sub classes. If you
want to create your own customized exceptions, then your class must extend this class.

14. Which class is the super class for all types of errors and exceptions in java?
[Link] is the super class for all types of errors and exceptions in java.

15. Define Process-based multitasking: (Multiprocessing)


A process is 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. In
process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.

16. Define Thread-based multitasking: (Multithreading)


In a thread-based multitasking environment, the thread is the smallest unit 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.

17. Differentiate between multitasking and multithreading.

Sl.n Multitasking Multithreading


o.

1 It is a process of executing many It is a process of executing multiple


processes running simultaneously. threads(sub- process).
2 Process is program in execution. They Thread is basically a lightweight sub-
are Heavy weight. process. It is a smallest unit of processing.
3 In multi tasking separate memory is Threads(sub-process) are sharing common
allocated to each process. memory.
4 Interprocess communication is Inter thread communication is inexpensive .
expensive
5 Context switching from one process to Context switching from one thread to another
another is costly. is inexpensive.

18. Define Multithreading.


Multithreading enables to write efficient programs that make maximum use of the processing power
available in the system. One important way multithreading achieves this is by keeping idle time to a minimum.

19. List are the States of thread.


• A thread can be running. It can be ready to run as soon as it gets CPU time.
• A running thread can be 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.

20. How can you create thread in Java?


Java defines two ways for creating thread.
1) By extending the Thread class.
2) By implement the Runnable interface.

21. What do you mean by synchronization?


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. Java
provides unique, language-level support for it.
Synchronization can be done in two ways:
1) Using Synchronized Methods
2) Using synchronized Statement or synchronized block
22. What is the need for synchronization?
The synchronization is mainly used to
• To prevent thread interference.
• To prevent consistency problem.

23. What is meant by monitor?


A monitor is an object that is used as a mutually exclusive lock. Only one thread can own a monitor at a
given time. 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.

24. How will you set the priority of the thread?


Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In
theory, higher-priority threads get more CPU time than lower-priority threads.
To set a thread’s priority, use the setPriority( ) method.
final void setPriority(int level)
The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these
values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is
currently 5.

Part-B
1. Develop a java program for handling divide by zero exception with multiple catches.
2. Develop a java program for handling ArrayIndexOutOfBoundsException exception with finally block.
3. Develop a java program for exception handling with throw and throws keyword.
4. Explain nested try/catch with example program.
5. Develop a java program with multiple catch clauses.
6. Develop a java program with multicatch that can handle both ArithmeticException and
IndexOutOfBoundsException.
7. Discuss about exception handling in nested try/catch.
8. Explain about types of exception with an example.
9. Develop a Java program to implement user defined exception handling.
10. Discuss the life cycle of threads with neat diagram.
11. Develop a program for creating threads by using Thread class and Runnable interface.
12. Why do we need both start() and run() method both? can we achieve it with only run() method?
13. Write a java program that synchronize three threads of the same program and display the content the
text supplied through these threads.
14. Develop a java program that provide synchronization for two threads deposit and withdraw in a bank
application.
15. Define thread. Explain the state of threads. State reason for synchronization in thread. Write simple
concurrent programming to create, sleep and delete thread.
16. What is thread synchronization? Discuss with an example.
17. Write a java program for inventory problem to illustrate the usage of thread synchronized keyword and
interthread communication process. They have three classes called consumer, producer and stock.
18. Write a java program that implements a multi-threaded application that has three threads. First thread
generates a random integer every 1 second and if the value is even, second thread computes the square of the
number and prints. If the value is odd, the third thread will print the value of cube of the number.
19. Develop a java application program for generating four threads to perform the following operation.
i) Getting N numbers as input
ii) Printing even numbers
iii) Printing odd numbers.
iv) Computing the average
20. Explain about wrapper classes.
21. Elaborate in detail about autoboxing.
22. Discuss about Suspending, Resuming, and Stopping Threads.

You might also like