Vous êtes sur la page 1sur 8

BLOCK-2

CH-4

EXCEPTION
An exception (or exceptional event) is a problem that arises during theexecution 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, below given are some scenarios where
exception occurs.
A user has entered 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.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Based on these we have three categories of Exceptions you need to understand them to know
how exception handling works in Java,
1. Checked exceptions: A checked exception is an exception that occurs at the compile
time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored at the time of compilation, the Programmer should take care of (handle)
these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the
file specified in its constructor doesn't exist, then anFileNotFoundException occurs, and
compiler prompts the programmer to handle the exception.

2. Unchecked exceptions: An Unchecked exception is an exception that occurs at the


time of execution, these are also called as Runtime Exceptions, these include
programming bugs, such as logic errors or improper use of an API. runtime exceptions
are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call
the 6th element of the array then anArrayIndexOutOfBoundsExceptionexception occurs.
3. Errors: These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error will
arise. They are also ignored at the time of compilation.
RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA
COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.

The Exception class has


ArithmeticException Class etc

many

subclasses

like

IOException,

RuntimeException,

Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks like
the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
a). The code which is prone to exceptions is placed in the try block, when an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block.
b). A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
c). The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
d). The finally block
RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA
COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks

User-defined Exceptions:
You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException
class.

BLOCK-3

CH-1

MULTI-THREADING

THREAD
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area. Thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.

MULTI-THREADING
Multithreading is a process of executing multiple threads simultaneously. A multi-threaded
program contains two or more parts that can run concurrently and each part can handle
different task at the same time making optimal use of the available resources specially when
your computer has multiple CPUs. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

THREAD LIFE CYCLE


A thread goes through various stages in its life cycle.

RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA


COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.

Ready: When a thread is created, it doesnt begin executing immediately. We must first
invoke start() method to start the execution. The thread is ready for execution.

Running: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.

Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.

Sleep: A runnable thread can enter the timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable state when that time interval expires or
when the event it is waiting for occurs.

Terminated ( Dead ): A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

THE MAIN THREAD


The 'main()' method in Java is referred to the thread that is running, whenever a Java program
runs. It calls the main thread because it is the first thread that starts running when a program
begins. Other threads can be spawned from this main thread. The main thread must be the last
thread in the program to end. When the main thread stops, the program stops running.
Main thread is created automatically, but it can be controlled by the program by using a Thread
object. The Thread object will hold the reference of the main thread with the help of
currentThread() method of the Thread class.

CREATING THREADS
In Java, a thread can be created in 2 ways:
i)
Implementing Runnable interface
ii)
Extending Thread Class
Both of these reside in Java.lang package.
RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA
COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

RUNNABLE INTERFACE
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

THE THREAD CLASS


Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
Thread()

Thread(String name)

Thread(Runnable r)

Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.

RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA


COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

6. public int getPriority(): returns the priority of the thread.


7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10.

public Thread currentThread(): returns the reference of currently executing


thread.

11.

public int getId(): returns the id of the thread.

12.

public Thread.State getState(): returns the state of the thread.

13.

public boolean isAlive(): tests if the thread is alive.

14.

public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.

15.

public void suspend(): is used to suspend the thread(depricated).

16.

public void resume(): is used to resume the suspended thread(depricated).

17.

public void stop(): is used to stop the thread(depricated).

18.

public boolean isDaemon(): tests if the thread is a daemon thread.

19.

public void setDaemon(boolean b): marks the thread as daemon or user


thread.

20.

public void interrupt(): interrupts the thread.

21.

public boolean isInterrupted(): tests if the thread has been interrupted.

22.

public static boolean interrupted(): tests if the current thread has been
interrupted.

THREAD PRIORITIES
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY
(a constant of 5).

RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA


COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and very much platform dependent.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.

INTER-THREAD SYNCHRONIZATION
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issue. For example if multiple threads try to write within a same
file then they may corrupt the data because one of the threads can overrite data or while
one thread is opening the same file at the same time another thread might be closing the
same file.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized methods & synchronized statements.
Synchronization provides a simple monitor facility that can be used to provide the mutual
exclusion between java threads.
SYNCHRONIZED METHODS: These are used to coordinate access to objects that are
shared among multiple threads. These methods are declared with the synchronized
keyword. Only one synchronized method can be invoked at a time. When a synchronized
method is invoked for a given object, it acquires a lock for that object. In this case no other
synchronized method may be invoked for that object until the lock is released. This keeps
synchronized methods in multiple threads without any conflicts with each other. A lock is
automatically released when the method completes it execution & returns.
SYNCHRONIZED STATEMENTS: An effective means of achieving synchronization is to
create synchronized methods with in the class. But it will not work in all cases, for example,
if you want to synchronize access to objects of a class that was not designed for
multithreaded programming or the class that doesnt use synchronized methods. In this
situation, the synchronized statement is a solution.
Synchronized statement iused to acquire a lock on an object before performing an action. It
is applied on a statement block rather than an entire method.

INTER-THREAD COMMUNICATION
Inter thread communication is important when you develop an application where two or
more threads exchange some information.

There are simply three methods which makes thread communication possible.
RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA
COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

Methods with Description


1

public void wait()


Causes the current thread to wait until another thread invokes the notify().

public void notify()


Wakes up a single thread that is waiting on this object's monitor.

public void notifyAll()


Wakes up all the threads that called wait( ) on the same object.

These methods have been implemented as final methods in Object, so they are
available in all the classes. All three methods can be called only from within
a synchronized context.

RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA


COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644

Vous aimerez peut-être aussi