Friday, 28 February 2014

Exploring Thread API

How to know the currently executing Thread
Thread API provides a method class currentThread(), which returns the reference of the currently executing thread

Syntax:
     public static Thread currentThread()

Since currentThread() is a static method, we can call it by using Thread class like
     Thread.currentThread()

Example
class MyThread extends Thread{
 public void run(){
  System.out.println("In run method, My name is " + currentThread());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  MyThread t2 = new MyThread();
  t1.start();
  t2.start();
  System.out.println("In main method, My name is " + Thread.currentThread());
 }
}
    
Possible Outcome 
In run method, My name is Thread[Thread-0,5,main]
In main method, My name is Thread[main,5,main] 
In run method, My name is Thread[Thread-1,5,main] 
 
Observation
See the format Thread[Thread-0,5,main]

Thread-0 : specifies the thread name, If you don't set a name to the Thread, it will follow default naming conventions

5 : Priority of the Thread., If you don't set a priority to a thread, by default it has 5, will

main : specifies the group name of the thread

Setting and get the name of a Thread
Every thread has a name associated with it. Thread API provides getName() and setName() methods to retrieve the thread name and set a name to thread respectively.

If user not set the name explicitly, then it will assign with a default name at the time of construction.

Setting a name to Thread
public final void setName(String name)
Changes the name of this thread to be equal to the argument name. Since the setName() is a final method, so you can't override it.

Getting the name of a Thread
public final String getName()
Returns this thread's name. Since the getName() is a final method, so you can't override it.

class MyThread extends Thread{
 public void run(){
  System.out.println("Current Runing Thread is " + Thread.currentThread());
  System.out.println("Current Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  t1.setName("MyThread1");
  t1.start();
 }
}

Output
Current Runing Thread is Thread[MyThread1,5,main]
Current Thread name is MyThread1


Points to be noted while setting the Thread name

1. Set the thread name before calling the start(). Of course you can can set the name to a thread after calling thread start method, but it is not preferable.

Example
class MyThread extends Thread{
 public void run(){
  System.out.println("Current Running Thread is " + Thread.currentThread());
  System.out.println("Current Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  t1.setName("MyThread1");
  t1.start();
  for(int i=0; i < 10000; i++){
   t1.setName("MyThread" + i);
  }
  System.out.println(t1.getName());
 }
}

Output
Current Running Thread is Thread[MyThread14,5,main]
Current Thread name is MyThread328
MyThread9999

See the above output in the bold letters, if thread name changed, when you are trying to perform some operations based on Thread name, then you will face problems.

2. Do not change the name of main thread. It will cause unexpected results

3. You can give same name to multiple threads, but give unique name to the threads, to identify differently



Create Thread by implementing runnable interface                                                 Thread consturctors                                                 Home

Creating Thread by implementing Runnable interface

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Runnable interface has only one method, i.e., run().

Prototype of run method is

public void run();

Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("I am in run method");
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.start();
 }
}

Output
I am in run method

Advantages of creating thread using Runnable as compared to extending Thread

1. By using runnable, you can create a task, and make number of threads to call it.
Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("I am in run method");
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  Thread t2 = new Thread(task);
  t1.start();
  t2.start();
 }
}

Output
I am in run method
I am in run method


2. If you create a thread by extending Thread class, then you are not allowed to extend any other class. Since java doesn't support multiple inheritance.


Create Thread by extending Thread class                                                 Exploring Thread API                                                 Home

Creating Thread by Extending Thread class

Creating a new thread is a 3 steps process

Step 1: Create a class by extending the Thread class
     Ex:
     class MyThread extends Thread{

     }

Step 2: Override the run method

Step 3: Call the start method of the Thread

Example
class MyThread extends Thread{
 public void run(){
  for(int i=0; i < 5; i++){
   System.out.println(i);
  }
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  t1.start();
 }
}
 
Output
0
1
2
3
4

Explanation
MyThread t1 = new MyThread();

Statement creates a thread object, and the reference t1 point to the object. When t1.start() is called it immediately call the run method and starts execution.

A Thread is alive until it finishes its execution (A Thread can stop its execution by calling its stop(), anyway it is deprecated).

Can I start a Thread twice ?
No

What will happen if I start a thread twice
Program will compile fine. But java run time throws IllegalThreadStateException at run time.

 Example
class MyThread extends Thread{
 public void run(){
  for(int i=0; i < 4; i++){
   System.out.println(i);
  }
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  t1.start();
  t1.start();
 }
}

Sample Output
0
1
2
3
4
Exception in thread "main" java.lang.IllegalThreadStateException
  at java.lang.Thread.start(Unknown Source)
  at MyThread.main(MyThread.java:13)

You may not see the output like above when you ran the progrm. Since you can't expect the output of an Asynchronous program.

Thread scheduling is non deterministic and depends on many factors, including what else is currently running in the operating system. I.e, you can't guess the outcome of threads.

class MyThread extends Thread{
 public void run(){
  for(int i=0; i < 5; i++){
   System.out.println("In My Thread " + i);
  }
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  t1.start();
  for(int i=0; i<5; i++){
   System.out.println("In Main Thread " + i);
  }
 }
}
   
Possible outcomes are:

Output for first run
In Main Thread 0
In Main Thread 1
In My Thread 0
In My Thread 1
In Main Thread 2
In My Thread 2
In Main Thread 3
In My Thread 3
In Main Thread 4
In My Thread 4

Output for next run
In Main Thread 0
In Main Thread 1
In Main Thread 2
In My Thread 0
In My Thread 1
In Main Thread 3
In My Thread 2
In Main Thread 4
In My Thread 3
In My Thread 4
  



Threads                                                 Create thread by implementing Runnable interface                                                 Home

Introduction To Threads in java

Simply Thread is called as a light weight Process.

Each thread has its own local variables, program counter, and its life cycle independent on other threads.

Even a simple Hello world application also multi threaded in Java. Whenever you starts an application, main thread is created and starts its execution, and garbage collector thread used to run in back ground.

By default main thread present in an application

Example
class MainThread{
 public static void main(String args[]){
  System.out.println(Thread.currentThread().getName());
 }
}

Output
main
   
Why to use Threads
a. To make the User Interface more responsive
b. To utilize the resources efficiently
c. To take the advantage of multiprocessor systems
d. To perform background processing tasks
e. To perform other operations, while one operation is waiting for I/O, or blocked etc.,


Extract info from stack trace element                                                 Create Thread by Extending Thread class                                                 Home

Extract information from StackTraceElement

StackTraceElement class provides method to extract the class name, method name, line number , file name from the given stack trace element.

public String getClassName()
Returns the fully qualified name of the class

public String getMethodName()
Returns the name of the method containing the execution point represented by this stack trace element.

public String getFileName()
Returns the name of the source file containing the execution point represented by this stack trace element.

public int getLineNumber()
Returns the line number of the source line containing the execution point represented by this stack trace element.

Example
class StackTraceEx{
 void divide(){
  try{
   int val = 10/0;
  }
  catch(ArithmeticException e){
   throw e;
  }
 }

 void show(){
  divide();
 }

 void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();

  try{
   obj.print();
  }
  catch(Exception e){
   StackTraceElement[] trace = e.getStackTrace();
   for(int i=0; i < trace.length-1; i++)
    System.out.println(trace[i].getClassName() +" " + trace[i].getFileName() +" " + trace[i].getMethodName() +" " + trace[i].getLineNumber());
   }
  }
}


Output
StackTraceEx StackTraceEx.java divide 15
StackTraceEx StackTraceEx.java show 22
StackTraceEx StackTraceEx.java print 25
   


Create stack trace element                                                 Threads in Java                                                 Home

How to create a stack trace element

Java provides StackTraceElement class to create stack trace element and to extract the details from stack trace element.

By using the constructor provided by the class StackTraceElement, we can create StackTraceElement.

public StackTraceElement(String declaringClass,
String methodName,
String fileName,
int lineNumber)

declaringClass - the fully qualified name of the class containing the execution point represented by the stack trace element

methodName - the name of the method containing the execution point represented by the stack trace element

fileName - the name of the file containing the execution point represented by the stack trace element, or null if this information is unavailable

lineNumber - the line number of the source line containing the execution point represented by this stack trace element, or a negative number if this information is unavailable. A value of -2 indicates that the method containing the execution point is a native method

Example
class StackTraceEx{
 static void show(){
  String className = "StackTraceEx";
  String methodName = "show";
  String fileName = "StackTraceEx.java";
  int lineNum = 9;
  StackTraceElement s1 = new StackTraceElement(className, methodName, fileName, lineNum);
  System.out.println(s1);
 }

 static void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj1 = new StackTraceEx();
  print();
 }
}
   
Output
StackTraceEx.show(StackTraceEx.java:9)
  

Stack trace Element                                                 Extract information from stack trace element                                                 Home

What is a Stack trace element

Each line in the stack trace represents Stack Trace Element. 

class StackTraceElement{
 void divide(){
  int var1 = 10/0;
 }

 void show(){
  divide();
 }

 void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceElement obj = new StackTraceElement();
  obj.print();
 }
}
   
When you run the above program, it generates “ArithmeticException” and JVM throws the stack trace like below.

Exception in thread "main" java.lang.ArithmeticException: / by zero
          at StackTraceElement.divide(StackTraceElement.java:4)
          at StackTraceElement.show(StackTraceElement.java:8)
          at StackTraceElement.print(StackTraceElement.java:12)
          at StackTraceElement.main(StackTraceElement.java:17)


Each line in the stack trace represents Stack Trace Element.
For Ex:
"StackTraceElement.divide(StackTraceElement.java:4)" is a Stack Trace Element.


Overriding vs Exception Handling                                                 Create Stack trace element                                                 Home