Tuesday, 31 March 2015

Multithreading in Java Session-4

Shutdown Hook

The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

When does the JVM shut down?

The JVM shuts down when:
  • user presses ctrl+c on the command prompt
  • System.exit(int) method is invoked
  • user logoff
  • user shutdown etc.

The addShutdownHook(Runnable r) method

The addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine. Syntax:
1.    public void addShutdownHook(Runnable r){}  


The object of Runtime class can be obtained by calling the static factory method getRuntime(). For example:
Runtime r = Runtime.getRuntime();

Factory method

The method that returns the instance of a class is known as factory method.

Simple example of Shutdown Hook

1.    class MyThread extends Thread{  
2.        public void run(){  
3.            System.out.println("shut down hook task completed..");  
4.        }  
5.    }  
6.      
7.    public class TestShutdown1{  
8.    public static void main(String[] args)throws Exception {  
9.      
10. Runtime r=Runtime.getRuntime();  
11. r.addShutdownHook(new MyThread());  
12.       
13. System.out.println("Now main sleeping... press ctrl+c to exit");  
14. try{Thread.sleep(3000);}catch (Exception e) {}  
15. }  
16. }  

Output:Now main sleeping... press ctrl+c to exit
       shut down hook task completed..
       
 

Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime class.


Same example of Shutdown Hook by annonymous class:

1.    public class TestShutdown2{  
2.    public static void main(String[] args)throws Exception {  
3.      
4.    Runtime r=Runtime.getRuntime();  
5.      
6.    r.addShutdownHook(new Runnable(){  
7.    public void run(){  
8.        System.out.println("shut down hook task completed..");  
9.        }  
10. }  
11. );  
12.       
13. System.out.println("Now main sleeping... press ctrl+c to exit");  
14. try{Thread.sleep(3000);}catch (Exception e) {}  
15. }  
16. }  

Output:Now main sleeping... press ctrl+c to exit
       shut down hook task completed..
       


How to perform single task by multiple threads?

If you have to perform single task by many threads, have only one run() method.For example:
Program of performing single task by multiple threads
1.    class TestMultitasking1 extends Thread{  
2.     public void run(){  
3.       System.out.println("task one");  
4.     }  
5.     public static void main(String args[]){  
6.      TestMultitasking1 t1=new TestMultitasking1();  
7.      TestMultitasking1 t2=new TestMultitasking1();  
8.      TestMultitasking1 t3=new TestMultitasking1();  
9.      
10.   t1.start();  
11.   t2.start();  
12.   t3.start();  
13.  }  
14. }  

Output:task one
       task one
       task one
Program of performing single task by multiple threads
1.    class TestMultitasking2 implements Runnable{  
2.    public void run(){  
3.    System.out.println("task one");  
4.    }  
5.      
6.    public static void main(String args[]){  
7.    Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of TestMultitasking2 class  
8.    Thread t2 =new Thread(new TestMultitasking2());  
9.      
10. t1.start();  
11. t2.start();  
12.   
13.  }  
14. }  

Output:task one
       task one


Note: Each thread run in a separate callstack.




How to perform multiple tasks by multiple threads (multitasking in multithreading)?

If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:
Program of performing two tasks by two threads
1.    class Simple1 extends Thread{  
2.     public void run(){  
3.       System.out.println("task one");  
4.     }  
5.    }  
6.      
7.    class Simple2 extends Thread{  
8.     public void run(){  
9.       System.out.println("task two");  
10.  }  
11. }  
12.   
13.  class TestMultitasking3{  
14.  public static void main(String args[]){  
15.   Simple1 t1=new Simple1();  
16.   Simple2 t2=new Simple2();  
17.   
18.   t1.start();  
19.   t2.start();  
20.  }  
21. }  

Output:task one
       task two

Same example as above by annonymous class that extends Thread class:

Program of performing two tasks by two threads
1.    class TestMultitasking4{  
2.     public static void main(String args[]){  
3.      Thread t1=new Thread(){  
4.        public void run(){  
5.          System.out.println("task one");  
6.        }  
7.      };  
8.      Thread t2=new Thread(){  
9.        public void run(){  
10.       System.out.println("task two");  
11.     }  
12.   };  
13.   
14.   
15.   t1.start();  
16.   t2.start();  
17.  }  
18. }  

Output:task one
       task two

Same example as above by annonymous class that implements Runnable interface:

Program of performing two tasks by two threads
1.    class TestMultitasking5{  
2.     public static void main(String args[]){  
3.      Runnable r1=new Runnable(){  
4.        public void run(){  
5.          System.out.println("task one");  
6.        }  
7.      };  
8.      
9.      Runnable r2=new Runnable(){  
10.     public void run(){  
11.       System.out.println("task two");  
12.     }  
13.   };  
14.       
15.   Thread t1=new Thread(r1);  
16.   Thread t2=new Thread(r2);  
17.   
18.   t1.start();  
19.   t2.start();  
20.  }  
21. }  

Output:task one
       task two

Garbage Collection:

In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically.

Advantage of Garbage Collection:

·         It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
·         It is automatically done by the garbage collector so we don't need to make extra efforts.

How can an object be unreferenced?

There are many ways:
·         By nulling the reference
·         By assigning a reference to another
·         By annonymous object etc.

1) By nulling a reference:

1.    Employee e=new Employee();  
2.    e=null;  

2) By assigning a reference to another:

1.    Employee e1=new Employee();  
2.    Employee e2=new Employee();  
3.      
4.    e1=e2;//now the first object referred by e1 is available for garbage collection  

3) By annonymous object:

1.    new Employee();  

finalize() method:

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in System class as:
1.    protected void finalize(){}  

Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).


gc() method:

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
1.    public static void gc(){}  

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.


Simple Example of garbage collection:

1.    public class TestGarbage1{  
2.      
3.     public void finalize(){System.out.println("object is garbage collected");}  
4.      
5.     public static void main(String args[]){  
6.      TestGarbage1 s1=new TestGarbage1();  
7.      TestGarbage1 s2=new TestGarbage1();  
8.      s1=null;  
9.      s2=null;  
10.   System.gc();  
11.  }  
12. }  

Output:object is garbage collected
       object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.


No comments:

Post a Comment

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...