Unit-3 Exception Handling, Multi Threading
Unit-3 Exception Handling, Multi Threading
Unit-3 Exception Handling, Multi Threading
Output:
java.lang.ArithmeticException: / by zero
rest of the code
EXAMPLE PROGRAM
class ExceptionThrowDemo
{
public static void main(String args[ ])
{int a=Integer.parseInt(args[0]); try
{
if(a>10)
{
throw new ArithmeticException("A is greater than 10");
}
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Program End");
}
}
JAVA THROWS
The Java throws keyword is used to declare an exception.
It gives an information to the programmer that there may occur an
exception so it is better for the programmer to provide the exception
handling code so that normal flow can be maintained
Exception Handling is mainly used to handle the checked exceptions
If there occurs any unchecked exception such as NullPointer
Exception, it is programmers fault that he is not performing check up
before the code being used
Syntax:
return_type method_name() throws exception_class_name
{
...
}
EXAMPLE:
import java.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
CONCEPTS OF MULTITHREADING
Multithreading is a powerful programming tool that makes java distinctly different
from its fellow programming languages.
The ability of executing several programs simultaneously is called
Multitasking.
The ability of executing several processes simultaneously is called
Multithreading.
THREAD
A Thread is simple process
A thread has a beginning, a body, and an end, and executes command
sequentially.
The entire main program can be called single-threaded programs.
Since threads in java share the same memory space, they are
known as Lightweight threads Or Lightweight processes.
‘Threads running in parallel’ does not mean they are running at the same time.
USES OF MULTITHREADING
Enables programmers to do multi things at a time.
A long program can be divided into threads and execute them in parallel.
Extensively used in java-enabled browsers as Hot. Java
NEWBORN STATE:
5. When we create the Thread object, the thread is born and is said to be in
Newborn state.
6. At this state we can do only one of the following,
7. Schedule it for running using start( ) method.
8. Kill it using stop( ) method.
RUNNABLE STATE:
5. The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor.
6. The process of assigning time to threads is known as time- slicing.
7. The first-come, first-serve manner is used here.
8. If we want to relinquish control to another thread to equal the priority
before it comes, we can use the yield( ) method
BLOCKED STATE:
3. A thread is said to be blocked when it is prevented from entering into
the runnable state and the running state.
4. A blocked thread is considered “not runnable” but not dead, and is fully
qualified to run again.
DEAD STATE:
4. A running thread ends its life when it has completed executing its run( )
method.
5. It is natural death.
6. A thread can be killed as soon as it is born, or while running or even
when it is in “not runnable “condition.
CREATING A NEW THREAD:
There are two ways,
1. by creating a thread class - Define a class that extends Thread class and
override its run( ) Method.
2. By converting a class to a thread – Define a class that implements Runnable
interface.
EXTENDING THE THREAD CLASS:
We can extend the class by using java.lang.Thread.
This gives access to all thread methods directly.
It includes the following:
1. Declare the class as extending the Thread class.
2. Implement the run( ) method for executing the Thread.
3. Create a thread object and class the start( ) method to initiate thread execution.
DECLARING THE CLASS:
The Thread class can be extended as follows:
class MyThread extends Thread
{
…………………
………………....
}
Now we have a new type of thread MyThread.
STARTING A NEW THREAD:
The syntax for creating and running an instance of the thread is as follows,
MyThread t1 = new
MyThread();
t1.start();
First line – instantiates a new object of class MyThread.
Second Line - calls the start( ) method causing the thread to move into the
runnable state.
EXAMPLE PROGRAM:
import java.lang.*;
class MyThreadA extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("MyThread 1 :"+i);
}
}
}
class MyThreadB extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("MyThread 2 :"+i);
}
}
}
public class ThreadExample
{
public static void main(String args[]) throws Exception
{
MyThreadA m1=new MyThreadA();
MyThreadB m2=new MyThreadB();
m1.start();
m2.start();
}
}
SYNCHRONIZATION IN JAVA
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.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. It can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
Java Synchronized Method
If you declare any method as synchronized, it is known as synchronized
method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its
task.
Suppose we have 50 lines of code in our method, but we want to synchronize only
5 lines, in such cases, we can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same
as the synchronized method.
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on
object.
Output:
Compile by: javac TestSynchronization4.java
Run by: java TestSynchronization4
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called
from the synchronized method only otherwise it will throw exception.
Method Description
public final void Waits until object is notified.
wait()throws’
InterruptedException
public final void wait(long timeout)throws Waits for the specified amount of time.
InterruptedException
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.
Syntax:
Public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by after the specified amount of time,
notify() or notifyAll() methods sleep is completed.
Example of inter thread communication in java
Let's see the simple example of inter thread communication.
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{
wait();
}
catch(Exception e){
}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){
c.withdraw(15000);} }.start();
new Thread(){
public void run(){
c.deposit(10000);}
}.start();
}}
Output:
Going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
ENUMERATION
Enumerations make for clearer and more readable code, particularly when
meaningful names are used. The benefits of using enumerations include: Reduces
errors caused by transposing or mistyping numbers. Makes it easy to change
values in the future.
AUTOBOXING
Converting a primitive value into an object of the corresponding wrapper class
is called auto boxing. For example, converting int to Integer class. The Java
compiler applies autoboxing when a primitive value is:
Passed as a parameter to a method that expects an object of the
corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
GENERICS
The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects.
Before generics, we can store any type of objects in collection i.e. non-generic.
Now generics, forces the java programmer to store specific type of objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety: We can hold only a single type of objects in generics. It
doesn’t allow to store other objects.
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList(); list.add("hello");
String s = (String) list.get(0);//typecasting After Generics, we don't need to
typecast the object.
List<String> list = new ArrayList<String>(); list.add("hello");
String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem
will not occur at runtime.
The good programming strategy says it is far better to handle the problem at
compile time than runtime.
List<String> list = new ArrayList<String>(); list.add("hello");
list.add(32);//Compile Time Error
Syntax to use generic collection
ClassOrInterface<Type>
Example to use Generics in java
ArrayList<String>
EXAMPLE OF GENERICS IN JAVA
Here, we are using the ArrayList class, but you can use any collection class such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
import java.util.*;
class TestGenerics1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
element is: jai rahul
jai
GENERIC CLASS
A class that can refer to any type is known as generic class. Here, we are using T
type parameter to
create the generic class of specific type.
Let’s see the simple example to create and use the generic class.
Creating generic class:
class TestGenerics3{
public static void main(String args[]){ MyGen<Integer> m=new
MyGen<Integer>(); m.add(2);
//m.add("vivek");//Compile time error System.out.println(m.get());
}}
Output: 2
GENERIC METHOD
Like generic class, we can create generic method that can accept any type of
argument.
Let’s see a simple example of java generic method to print array elements. We are
using here E to
denote the element.