Core Java - [Thread Life Cycle]

♠ Posted by Unknown in

Thread Life Cycle and Example


During the life time of a thread, there are many states it can enter. They include:
1.      Newborn State
2.      Runnable State
3.      Running State
4.      Blocked State
5.      Dead State

A thread is always in one of these five states. It can move from one state to another via a variety of ways. Shown in below figure.

Image: Java Thread Life Cycle

1.      Newborn State :

When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it:
·         Schedule it for running using start() method.
·         Kill it using stop() method.

2.      Runnable State :

The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is the thread has joined the queue of threads that are waiting for execution. If all threads have equal priority, then they are given time slots for execution in round robin fashion, i.e. first-come, first-serve manner. The thread that relinquishes control joins the queue at the end and again waits for its turn. This process of assigning time to threads is known as time-slicing.
However, if we cant a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using the yield() method.

3.      Running State :

Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquish its control in one of the following situations.
·         It has been suspended using suspend() method. A suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it.
·         It has been made to sleep, we can put a thread to sleep for a specified time period using the method sleep(time) where time is in milliseconds. This means that the thread is out of the queue during this time period. The thread re-enters the runnable state as soon as this time period is elapsed.
·         It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method.

4.      Blocked State :

A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. this happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

5.      Dead State :

Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition.

When we start any Java Program, one thread begins running immediately, which is called the "main thread" of that program. Within the main thread of any Java program you can create other "child" threads.
The Main thread is created automatically when your program is started. The main thread of Java Programs is controlled through an object of "Thread" Class.

The multithreaded programming in Java is built upon the "Thread Class", its methods and its companion Interface "Runnable". To create a new thread, your program will either extend "Thread" class or implement the "Runnable" interface.

Thread Class Methods :


Some commonly used methods of Thread class are given below:

1. currentThread() :
            Returns reference to the currently executing thread object.
2. getName() :
            Returns the name of the thread in which it is called.
3. getPriority() :
            Returns the Thread's priority
4. interrupt() : Used for Interrupting the thread.
5. interrupted() : Used to check whether the current thread has been interrupted or not.
6. isAlive() : Used for testing whether a thread is alive or not.
7. setName() : Changes the name of the thread to NewName.
8. setPriority() : Changes the priority of thread.
9. sleep() :  Causes the currently executing thread to sleep for the specified number of microsecond.
10 start() : Used to begin execution of thread. The java virtual machine calls the run method of the thread in which this method is called.
11. toString() : Returns a string represntation of thread.
12. yield() : Used to pause temprarily to currently executing thread object and allow other threads to execute.
13. activeCount() : Returns the number of active threads in the current thread's thread group.
14. destroy() : Destroys the thread without any cleanup.

Example :

import java.io.*;
import java.lang.*;
class MyThread implements Runnable
{
            private char c;
            private int times;
           
            public MyThread(char x, int n)
            {
                        c = x;
                        times = n;
            }

            public void run()
            {
                        for(int i = 1; i<= times; i++)
                        {
                                    System.out.println(c + " character is " + i + " times....");
                        }
            }
};
public class  ThreadExample
{
            public static void main(String[] args)
            {
                        MyThread th1 = new MyThread('A',10);
                        MyThread th2 = new MyThread('B',10);

                        th1.setPriority(Thread.MIN_PRIORITY);
                        th2.setPriority(Thread.MAX_PRIORITY);

                        th1.start();
                        th2.start();
            }
}



Core Java - [Multithreading Fundamentals]

♠ Posted by Unknown in

Multithreaded Programming in Java


Multithreading is a conceptual programming paradigm where a program (process) is divided into two or more subprograms (processes), which can be implemented at the same time in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. This is something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously.

A thread is similar to a program that has a single flow of control. It has a beginning, a body, and an end, and executes commands sequentially. In fact all main programs can be called single-threaded programs.

The main thread is actually the main method module, which is designed to create and start the other three threads, namely A, B, and C.

Once initiated by the main thread, the threads A, B, and C run concurrently and share the resources jointly. The ability of a language to support multithreads is referred to as concurrency. Since threads in Java are subprograms of a main applications program and share the same memory space, they are known as lightweight threads or lightweight processes.

Threads are extensively used in Java-Enabled browsers such as HotJava. These browsers can download a file to the local computer, display a Web Page in the window, output another Web page to a printer and so on.

CREATING THREADS :

Creating threads in Java is simple. Threads are implemented in the form of objects that contain a method called run(). The run() method is the heart and soul of any thread. It makes up the entire body of the thread and is the only method in which the thread’s behavior can be implemented.

                        public void run()
                        {
                                    …………
                                    ……….. (statements for implementing thread)
                                    ………..
                        }

The run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another thread method called start().

A new thread can be created in two ways.
1.      By creating a thread class: Define a class that extends Thread class and override its run() method with the code required by the thread.
2.      By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run (), that is to be defined in the method with the code to be executed by the thread.

Core Java - [Exception-02]

♠ Posted by Unknown in

Exception handling Examples

When Runtime Error occurred in program can be terminated abnormally and cannot display output or proper error message.

So, at runtime if program can be terminated without inform any error that can be understand by programmer, it is very crucial to find an error in program or taken output.

If programmer can be expected that error in his code it can be handled by the java exception handling method.

Java will help the programmer to handle exception using following five keywords : try, catch, throw, throws, and finally.

Syntax :

try.....catch :

try
{
            Exception expected
            code segment;
}
catch(exception object)
{
            when exception occurred
            code segment;
}

try with multiple catch block

try
{
            Exception expected
            code segment;
}
catch(exception object)
{
            when exception occurred
            code segment;
}
catch(exception object)
{
            when exception occurred
            code segment;
}

try with multiple catch and finally

try
{
            Exception expected
            code segment;
}
catch(exception object)
{
            when exception occurred
            code segment;
}
catch(exception object)
{
            when exception occurred
            code segment;
}
finally
{
            Code Segment that must be executed
            either exception is raised or not.
}

finally blocked must be written last in the try...catch block.

Example :

import java.lang.*;
import java.io.*;
class  TryExample1
{
            public static void main(String[] args)
            {
                        int a, b, c;
                        try
                        {
                                    a = Integer.parseInt(args[0]);
                                    b = Integer.parseInt(args[1]);
                                    c = a + b;
                                    System.out.println("The Sum is : " + c);
                        }
                        catch(ArrayIndexOutOfBoundsException e)
                        {
                                    System.out.println("You cannot use args[] in proper way...");
                        }
                        catch(NumberFormatException e)
                        {
                                    System.out.println("You cannot Enter Numeric values for Variables....");
                        }
                        finally
                        {
                                    System.out.println("This Block Expected Any Time....");
                        }
            }
}

Core Java - [Exception-01]

♠ Posted by Unknown in

Exception: List the Common Java Exceptions.

An exception is a condition that is caused by a run-time error in the program. When the Java interpreter encounter an error such as dividing an integer by zero, it creates an exception object and throws it (i.e., informs us that an error has occurred).

If the exception object is not caught and handled properly, the interpreter will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as exception handing.

The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstance” so that appropriate action can be taken. The mechanism suggests incorporation of a separate error handling code that performs the following tasks:
                       
                        Find the problem (Hit the exception)
                        Inform that an error has occurred (Throw the exception)
                        Receive the error information (Catch the exception)
                        Take corrective actions (Handle the exception)

The error handling code basically consists of two segments, one to detect errors and to throw exceptions and the other to catch exceptions and to take appropriate actions.

Common Java Exceptions :

Exception Type
Cause of Exception

ArithmaticException

Caused by math errors such as division by zero

ArrayIndexOutOfBoundsException

Caused by bad array indexes

ArrayStoreException

Caused when a program tries to store the wrong type of data in an array

FileNotFoundException

Caused by an attempt to access a nonexistent file

IOException

Caused by general I/O failures, such as inability to read from a file.

NullPointerException

Caused by referencing a null object.

NumberFormatException

Caused when a conversion between strings and number fails

OutOfMemoryException

Caused when there’s not enough memory to allocate a new object.

SecurityException

Caused when an applet tries to perform an action not allowed by the browser’s security setting.

StackOverflowException

Caused when the system runs out of stack space.

StringIndexOutOfBoundsException

Caused when a program attempts to access a nonexistent character position in a string.

There are two types of Exception in Java.

  1. Checked Exception:-

The Checked Exceptions are those Exceptions which are known at compile time and programmer knows that it must be handled to execute his java code. This kind of exceptions are throws by java methods so, code can be executed smoothly or written into try..catch block to display proper message and run the program on further coding.

The Checked Exceptions are available into Throwable package->Exception class and its sub classes Exception, excepts RuntimeException class.

The Example of Checked Exception is IOException, ClassNotFoundException, SQLException, etc....

  1. UnChecked Exception :-

The Unchecked Exceptions are those Exceptions which are expected at runtime in code segment of java program. The programmer can be guessed his code segment and put it in the try...catch block and if runtime exception occurred by user of that code the catch block can be directed on write error message and program cannot be terminated and go further execution.
The UnChecked Exceptions are available into Throwable Package->Exception Class -> RuntimeException Class and Its Subclasses.

The Example of UhChecked Exceptions are ArrayIndexOutofBoundExcep tion, NumberFormatException, NullPointerException, etc....

Core Java - [Wrapper Class]

♠ Posted by Unknown in

Wrapper Class


The vectors cannot handle primitive data types like int, float, long, char,  and double. Primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package. Below table shows the simple data types and their corresponding wrapper class types.

Simple Type

Wrapper Class

boolean

Boolean

char

Character

double

Double

float

Float

int

Integer

long

Long



Converting Primitive to Objects Using Constructor
Converting Objects to Primitive using method
Converting Numbers to Strings
Converting String objects to Numeric objects
Converting Numeric Strings to Primitive Numbers
Integer IntVal = new Integer()
int i =  IntVal.intValue()
str = Integer.toString(i)
IntVal = Integer.valueOf()
int i = Integer.parseInt(str)
Float FloatVal = new Float()
float f = FloatVal.floatValue()
str = Float.toString(f)
FloatVal = Float.valueOf()
long l = Long.parseLong(str)
Double DoubleVal = new Double()
double d =  DoubleVal.doubleValue()
str = Double.toString(d)
DoubleVal = Double.valueOf()

Long LongVal = new Long()
long l = LongVal.longValue()
str = Long.toString(l)
LongVal = Long.valueOf()



The Wrapper classes have number of methods for handling primitive data types and objects.

Core Java - [Vector Class]

♠ Posted by Unknown in

Vector class


The Vector class contained in the java.util package. This class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number. The objects do not have to be homogenous. Arrays can be easily implemented as vectors. Vectors are created like arrays as follows:
                       
                        Vector intVect = new Vector(); //declaring without size
                        Vector list = new Vector(3); //declaring with size

The vector can be declared without specifying any size explicitly. A vector can accommodate an unknown number of items. Even, when a size is specified, this can be overlooked and a different number of items may be put into the vector. Remember, in contrast, an array must always have its size specified.

Vectors possess a number of advantages over arrays.
1.      It is convenient to use vectors to store objects.
2.      A vector can be used to store a list of objects that may vary in size.
3.      We can add and delete objects from the list as and when required.

A major constraint in using vectors is that we cannot directly stores simple data types in a vector; we can only store objects.

list.addElement(item)

Adds the item specified to the list at the end

list.elementAt(10)

Gives the name of the 10th object

list.size()

Gives the number of objects present

list.removeElement(item)

Removes the specified item from the list

list.removeAllElements()

Removes the item stored in the nth position of the list

list.copyInto(array)

Copies all items from list to array

list.insertElementAt(item, n)

Inserts the item at nth position

import java.util.*;

class  LanguageVector
{
                        public static void main(String[] args)
                        {
                                    Vector list = new Vector();
                                    int length = args.length;

                                    for(int i = 0; i < length; i++)
                                    {
                                                list.addElement(args[i]);
                                    }

                                    list.insertElementAt("COBOL", 2);
                                    int size = list.size();
                                    String listArray[] = new String[size];
                                    list.copyInto(listArray);
                                    System.out.println("List of Languages");

                                    for(int i = 0; i < size; i++)
                                    {
                                                System.out.println(listArray[i]);
                                    }
                        }
}