Let's explore java

Monday, August 01, 2011

Exception handling

First of all we should learn that what exception exactly means? Exceptions are the events occured by the java run time system or the user programmer which disrupts the normal flow of the program.
Java run time system implements a technique called exception handling which examines the program for the correct execution of the program.Exception handling is the method when if any problem occures in the programming then the execution disrupts and the cause of the exception are being displayed.Throwable is the main built in class for all other subclasses of the exception.
Throwable-->Exception-->RuntimeException....this is the class hierarchy how the exception classes works.
Suppose any perticular programming shows the runtime exception and user did not explictly implemented the exception handler then java run time system implements default exception handler.
The program will explain you in the best possible way.

class default {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Here in this program when java run time system finds that there is an attempt to divide by zero then it creats the exception object and throws the exception.When the exception has been thrown the execution ofthe program stops because once the exception has been thrown it must be caught by a exception handler defined by user.Here what we find that there is no any exception handler by the user so java run time system creates the default exception handler which catch this exception and displays the string describing about the exception.Here is the output when this program is being executed:-
java.lang.ArithmeticException: / by zero
at default.main(default.java:4)
Although java's default handler is the good way to debug and fix the problem occured in the program but sometime user himself wants to fix the problem by using explictly exception handler.There are two benifits when explicetly defining the exception handler.
1)you can fix the problem in the most easiest way.
2)you can prevent the program from terminating .
To guard and debugg against the run time exception just embed the programming with try block which throws the exception whenever it occures and at the end there must be catch statement which catches the exception and debugging starts.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
we will continue from here in the next blog post.
thank you for your devotion towards java....hava a nice day...

Friday, May 13, 2011

multithreading in java


Multithreaded programming
Unlike any other programming languages java provides built-in support for the multithreaded programming. Multitasking can be accomplished easily with the help of multithreaded programming in java. Multithreaded programming contain two or more then two parts which can be run concurrently. Each part is defined as thread. Each thread defines the separate executing path. Multithreaded programming means a small program can perform two or more operation simultaniosly.  The idle time of the CPU can be best managed with the help of this concept in java. The Idle time of the cpu can be utilized for executing other part of the programs. Thread exists in several states such as running state, ready to use state, and suspended states.

The main thread

When a java program run then the one thread immideatly run .This is mainly called as the main thread. It has mainly two uses. First  many child thread can be generated from this main thread and second generally main thread is the last thread to be accomplished because it generally performs various shutdowns
//controlling the main thread
class CurrentThreadDemo
            {
                        public static void main(String args[])
                        {
                                    Thread t=Thread.currentThread();
                                    System.out.println("Current thread:"+t);
//change the name of the thread
                                    t.setName("My thread");
                                    System.out.println("After the name changed"+t);
            try
            {
                        for(int n=5;n>0;n--)
                        {
                                    System.out.println(n);
                                    Thread.sleep(1000);
                        }
                        }
catch(InterruptedException e)
{
            System.out.println("Main thread interrupted");
}
}
}
In this program the reference to the current thread is obtained by the currentThread(). And its reference is assigned to the local variable t. then program display the information about the thread. Then setName() function is use to change the name of the current thread and again the information about the current thread is displayed. The pause is accomplished by the calling of the method sleep(). The aggument to the sleep() method specify the time till suspension.  Thread might throw some exception .
//create a second thread
Thread can also be created  and we can do it by instantiating an object of type Thread. There are two ways in which Threads can be created.
1)by implementing Runnable interface
2)By extending Thread class,itself

                                                 Implementing Runnable

We can create Thread on any object which implements 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. After a class which implements Runnable is created,we will instantiate an object of type Thread from within that class. Thread defines several constructors .The one we will use is shown here:
Thread(Runnable threadob,string threadName)
After 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().
class NewThread implements Runnable
                {
                                Thread t;
                                NewThread()
                                                {
                                                                t=new Thread(this,"Demo thread");
                                                                System.out.println("Child Thread: "+t);
                                                                t.start();
}
//This is the entry point for the second thread.
public void run()
                                                                                {
                                                                                                try
                                                                                                                {
                                                                                                                                for(int i=5;i<0;i--)
                                                                                                                                {
                                                                                                                                                System.out.println("ChildThread: "+i);
                                                                                                                                                Thread.sleep(500);
                                                                                                                                }
                                                                                                                }
                                                                                                catch(InterruptedException e)
                                                                                                                                {
                                                                                                                                                System.out.println("Childinterrupted");

                                                                                                                                }
                                                                                                                System.out.println("Existing child thread");
                                                                                                                }
                                                                                }
                                                                class ThreadDemo
                                                                                {
                                                                                                public static void main(String args[])
                                                                                                {
                                                                                                                new NewThread();
                                                                                                                try
                                                                                                                {
                                                                                                                for(int i=5;i<0;i--)
                                                                                                                {
                                                                                                                System.out.println("Main thread: "+i);
                                                                                                                Thread.sleep(1000);
                                                                                                                }
                                                                                                                }
                                                                                                                catch(InterruptedException e)
                                                                                                                {
                                                                                                                System.out.println("main thread interrupted");
                                                                                                                }
                                                                                                                System.out.println("main thread exiting");
                                                                                                }
                                                                                                }
Passing this as the first argument indicates that you want the new thread to call the run() method on this object. Next start() is called, which starts the thread of execution beginning at the run()method

Extending Thread

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin execution of the new thread. Here is the pereciding program rewritten to extend Thread:
class newthread extends Thread
{
newthread()
{
super("Demo Thread");
System.out.println("child thread: "+this);
start();
}
public void run()
                                                                                {
                                                                                                try
                                                                                                                {
                                                                                                                                for(int i=5;i>0;i--)
                                                                                                                                {
                                                                                                                                                System.out.println("ChildThread: "+i);
                                                                                                                                                Thread.sleep(500);
                                                                                                                                }
                                                                                                                }
                                                                                                catch(InterruptedException e)
                                                                                                                                {
                                                                                                                                                System.out.println("Childinterrupted");

                                                                                                                                }
                                                                                                                System.out.println("Existing child thread");
                                                                                                                }
                                                                                }
                                                                class extendsdemo
                                                                                {
                                                                                                public static void main(String args[])
                                                                                                {
                                                                                                                new newthread();
                                                                                                                try
                                                                                                                {
                                                                                                                for(int i=5;i>0;i--)
                                                                                                                {
                                                                                                                System.out.println("Main thread: "+i);
                                                                                                                Thread.sleep(1500);
                                                                                                                }
                                                                                                                }
                                                                                                                catch(InterruptedException e)
                                                                                                                {
                                                                                                                System.out.println("main thread interrupted");
                                                                                                                }
                                                                                                                System.out.println("main thread exiting");
                                                                                                }
}

Creating Multiple Threads

We can create Multiple threads as well and this is best explained with the help of the following programming.
class Newthread implements Runnable
{
string name;
Thread t;
Newthread(String nname)
{
name=nname;
t=new Thread(this,name);
System.out.println("new Thread"+t);
t.start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println(name+":" +i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name+"interrupted");
}
System.out.println(name+"exited");
}
}
class Multithread
{
public static void main(String args[])
{
new Newthread("one");
new Newthread("two");
new Newthread("three");
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("main Thread exited");
}
}

Using isAlive() and join()

Often we want the main thread to finish last. In the preceding examples. This is accomplished by calling sleep() within main(), with a long enough delay to ensure that all child threads terminate prior to the main thread.Two ways exist to determine whether a thread has finished. First, you can call isAlive() on the thread. This method is defined by Thread, and its general form is shown here:
final Boolean isAlive()
Some times the main thread has to wait for the new thread or child thread to finish its execution and this is done through the use of method called join()
final void join()
//using join() to wait for threads to finish.
class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String threadname)
{
name=threadname;
t=new Thread(this,name);
System.out.println("New THread: "+t);
t.start();
}
//this is the entry point for the thread
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println(name+" :"+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name+"interrupted");
}
System.out.println(name+"exited");
}
}
class DemoJoin
{
public static void main(String args[])
{
NewThread ob1=new NewThread("one");
NewThread ob2=new NewThread("two");
NewThread ob3=new NewThread("three");
System.out.println("Thread one is alive?"+ob1.t.isAlive());
System.out.println("Thread two is alive?"+ob2.t.isAlive());
System.out.println("Thread three is alive?"+ob3.t.isAlive());
//wait for thread to finish
try
{
System.out.println("Waiting for the thread to finish");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Thread one is alive?"+ob1.t.isAlive());
System.out.println("Thread two is alive?"+ob2.t.isAlive());
System.out.println("Thread three is alive?"+ob3.t.isAlive());
System.out.println("Main thread is exiting");
}
}

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 threads get more cpu time than lower priority threads. To set the thread’s priority, use the setPriority() method,which is a member of Thread. This is its general form:
final void setPriority(int level).      Here level,specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY
 
//demonstrate thread priorities
class Clicker implements Runnable
{
long click=0;
Thread t;
private volatile boolean running=true;
public Clicker(int p)
{
t=new Thread(this);
t.setPriority(p);
}
public void run()
{
while(running)
{
click++;
}
}
public void stop()
{
running=false;
}
public void start()
{
t.start();
}
}
class HiLopri
{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Clicker hi=new Clicker(Thread.NORM_PRIORITY+2);
Clicker lo=new Clicker(Thread.NORM_PRIORITY-2);
lo.start();
hi.start();
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
lo.stop();
hi.stop();
//wait for child threads to terminate.
try
{
hi.t.join();
lo.t.join();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Low priority thread: "+lo.click);
System.out.println("high priority thread: "+hi.click);
}
}