Sunday 18 September 2011

Multi Threading in Java

What is Thread.?
Process is program in execution.. It contains set of threads.
thread has its own stack and register and share some resources with the another thread. All threads simulates to run concurrently increases the responsiveness of the program. There is a scheduling algorithm which switches the thread .
Used when we want to few things simultaneously like downloading one thing at same time surfing the internet.
How to create thread in Java .?
JVM creates a main thread when program is just started.
Thread is like any normal object that has member, resides on heap.
In java, you can define and instantiate thread by
1. Extending the Thread class
2. implementing the Runnable class
1.  By extending Thread class
You should override the run() of Thread class . Place piece of code that u want to run in separate thread in run() method that you override.
Disadvantage  is that you can extend anything else if you extend Thread class.
class DemoThread extends Thread
{
public void run()
{
//put ur code here that u want to run in separate thread
       // u r free to overload run if u want
}
}
2. implementing Runnable class
class DemoThread implements Runnable
{
public void run()
{
/*put ur code here that u want to run in separate thread*/
       // u r free to overload run if u want
}
}
Instantiating a Thread
Thread class implements Runnable.
You can instantiate as :
Thread t=new Thread(new Runnable(){public void run(){}});
or
Thread t=new Thread(new DemoThread());
Thread constructor takes an argument af any class that implements Runnable interface.
you can also create multiple thread.
Runnable r=new DemoThread();
Thread t1=new Thread(r);// Thread 1
Thread t1=new Thread(r);//Thread 2
Thread t1=new Thread(r);// Thread 3

Starting a Thread
Means to give a thread new stack to run code placed inside run(). This is accomplished by
t.start(). After starting thread doesn’t means that it starts running. It will run when it get chance to execute. That is when start a thread , it moves to runnable state.
State of thread
1. new state---Thread object is created
2. runnable state: when start() is called and new stack is allocated to that thread
3. running—when it gets a chance to run
4. waiting—when blocked because it is unable to run, waiting for resource.
5. Dead---after run() is executed completely . Dead thread cannot be started again.
You cannot start thread again after it is dead. Does this will cause InvalidStateException.
t.start();
t.start();//try this will cause exception
Naming a thread
Constructors of thread:
Thread()
Thread(String s)
Thread(Runnable r)
Thread(Runnable r,String s)
setting a name:
DemoThread t=new DemoThread(“milan”);
or
t.setName(milan);
getting Name of thread
String s=t.getName();
Notes:
Behaviour of thread is not gurranteed . JVM has algorithm  which decided which thread to run.
Multithread is vast topic. So I will continue in next session. 


Sunday 11 September 2011

static import


Used when you want to use class static members.
1. import static java.lang.System.out;/*imports the static instance “out”.*/
now u can use “out” as:
out.println(“My name is Milan”);
2. import static java.lang.Integer.*; /*imports all the static method and variable of class Integer*/
now u can use static member of Interger as:
System.out.println(MAX_VALUE);
System.out.println(toHexString(4248));
3. import static java.lang.System.*;/*imports all the static methods and var of class System*/
Rules
1.import static java.lang.System.out.*;/*Compiler error. U cant do static imports  on static reference,var or methods*/
2.If u do static imports on both Integer and Long class.Both class has Static var MAX_VALUE so there will be compiler error
3.static import java.lang.Integer.*; /*Compiler error cannot write “static import” instead of “import static”*/

Disadvantage
Program becomes less readable.

Thursday 8 September 2011

Sequence in which static initialization block, initialization block, constructors are called


1.Static initialization blocks are called even if object of that class in never created. If class which has a Static initialization blocks is having any relation(isA/hasA) directly or indirectly with the main class, than Static initialization blocks is called.Static initialization blocks are called first. Very Super Class Static initialization blocks are called, than its subclass Static initialization blocks are called and so on...
2.initialization blocks are called before constructor means before any object of that class is created and after Static initialization blocks.
3.Subclass constructor has its 1st statement either call to super() or this(), but not both. By default super() is called if nothing is specified. If you have defined no constructor in your class , than by default compiler inserts a no arg constructor in your class . If you have defined a constructor in your class , than compiler will not insert any constructor in your class. That is if you have defined arg constructor , than you will have to define no arg constructor ,dont expect compiler to define for you. 




Here is a program than shows sequence in which  static initialization block, initialization block, constructors are called
This is important concepts for those who is preparing for scjp exam and also for those who are working as core java developer.


class
A {
{ System.out.print("b1 "); }
public A() { System.out.print("b2 "); }
}

class B extends A {
static { System.out.print("r1 "); }
public B() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}

public class Test9 extends B {
public static void main(String[] args) {
System.out.print("pre ");
new Test9();
System.out.println("post ");
}
}
output:
r1 r4 pre b1 b2 r3 r2 post

Please comment if you find my article helpful.

Tuesday 6 September 2011

clone() method of Object class

 clone() is method of  Object Class. It is overridden in class that implements Cloneable interface. 
It is used to make a copy of object and set properties of object as required so that we do not have to create new object each time we need and set its properties.

Class that contain only primitive instance can be cloned easily by implementing Cloneable interface and overriding clone() method. But if Class also contains instance of another Class, than that Class should also implement an Cloneable interface and override clone() method. Otherwise Copy of object will not be created and exception will be thrown CloneNotSupportedException and no new Object of that class will be created .
Program 1 :

class Person implements Cloneable {
private Car car;
private String name;
private Integer no;

public Car getCar() {
return car;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Person(Integer n, String s, String t) {
no = n;
name = s;
car = new Car(t);
}
public Object clone() {
// shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {//exception will be thrown so null will be returned & no           //object      will     be created
return null;
}
}
public void setNo(Integer no) {
this.no = no;
}
public Integer getNo() {
return no;
}
}

class Car {

private String name;

public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Car(String s) {
name = s;
}
}

public class ShallowCopyTest {

public static void main(String[] args) {
// Original Object
Person p = new Person(new Integer(1000), "sreeRama", "Garuda");
System.out.println("Original (orginal values): " + p.getNo() + " "
+ p.getName() + " - " + p.getCar().getName());
// Clone as a shallow copy
Person q = (Person) p.clone();
System.out.println("Clone (before change): " + q.getNo() + " "
+ q.getName() + " - " + q.getCar().getName());
// change the primitive member
q.setName("Indra");
q.setNo(new Integer(2000));
// change the lower-level object
q.getCar().setName("Iravath");
System.out.println("Clone (after change): " + q.getNo() + " "
+ q.getName() + " - " + q.getCar().getName());
System.out.println("Original (after clone is modified): " + p.getNo()
+ " " + p.getName() + " - " + p.getCar().getName());
}
}
//output :
Original (orginal values): 1000 sreeRama - Garuda
Clone (before change): 1000 sreeRama - Garuda
Clone (after change): 2000 Indra - Iravath
Original (after clone is modified): 1000 sreeRama - Iravath

Program 2
class Person implements Cloneable {
// Lower-level object
private Car car;//it implements cloneable and override clone()
private String name;

public Car getCar() {
return car;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Person(String s, String t) {
name = s;
car = new Car(t);
}
public Object clone() throws CloneNotSupportedException{
// Deep copy
Person p = (Person) super.clone();
p.car = (Car) p.car.clone();
return p;
}
}
class Car implements Cloneable{

private String name;

public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Car(String s) {
name = s;
}
@Override
protected Object clone() throws CloneNotSupportedException {//everything is perfect
return super.clone();
}
}
public class DeepCopyTest {

public static void main(String[] args) {
// Original Object - before Deep cloning
Person p = new Person("sreeRama", "Garuda");
System.out.println(p.getName()+" "+p.getCar().getName());
Person pClone = null;
try {
pClone = (Person) p.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println("Clone (before change): "+pClone.getName()+" "+pClone.getCar().getName());
pClone.setName("Indra");
pClone.getCar().setName("Iravath");
System.out.println("Clone (after change): "+pClone.getName()+" "+pClone.getCar().getName());
// Original Object - after Deep cloning
System.out.println(p.getName()+" "+p.getCar().getName());
}
}
// Output :
sreeRama Garuda
Clone (before change): sreeRama Garuda
Clone (after change): Indra Iravath

Monday 5 September 2011

equals() and hashCode() method of Object Class

Object is super class all the classes. So a class can override equals() and hasCode() method of Object class.
When we want to make two different object of a class meaningful equal, we should override equals() method of object in that class.

class Test
{
 int var;
public boolean equals(Object o)
{
if((o instanceOf Test) && ((Test)o.var==this.var))
{
return true;
}else{
return false;
}
}
public int hashCode(){
return x*7;
}
}
here is sample program that shows how to override equals method.

2.hashCode(): It is used by Collection to find the object efficiently. It is used by HashMap, HashTable, etc classes of collection to find the object of a class from Collection efficiently. HashCode should be different for meaningfully different object for efficiency. It is legal to have same hashCode for all object of a class, but it is not efficient while searching using a Collection.

Hope that you might find my article helpfully . For further understanding please read SCJP Book by Kathy Sierra. Will write such good & important topics related to scjp exam daily.


Saturday 3 September 2011

Basic Stuff that all java programmer should know

All Objects resides in heap in JAVA.

Animal a;

here we have created a reference of class Animal. 'a' is reference which contains the address of object that it points to. Since currently 'a' is not pointing to any object ,'a' contains the null pointer.


a=new Animal();

now reference 'a' will point to object of animal created on heap.

So When does the object become eligible for garbage collection. Garbage collection is memory management technique used by JVM. Where there is no reference to object, that object becomes eligible for GC. We can request JVM to run GC  .

1.System.gc();
 2.Runtime r = Runtime.getRuntime();     r.gc();

when we make a=null; .the object 'a' is referring will have no reference  . So that object  becomes eligible for GC. Remember We can request JVM to run GC but cannot force.
The questions asked in scjp are like how many object will become eligible for gc given some code. So understanding this topic is very important. If you have any query you can contact to milan.ashara@yahoo.com.


SCJP Preparation

I will post daily the necessary points to guide you while preparing for scjp. First of all what is scjp.? who should give scjp.?.

All the details about scjp can be found at http://java.sun.com/new2java/articles/certification.html.

 I am working as software engineer and also preparing for scjp. If you have any query about anything regarding scjp please feel free to contact me at milan.ashara@yahoo.com.