Java Threads by Extending Thread class and Implementing Runnable Interface

 
Today we will discuss about the Threads in Java. Java Threads are nothing but multiple light weight execution under single process where all Threads will share same resources and runs independently. Most of all operatiing systems will support Threads and each and every Java programs are running atleast with single Thread. For example when Hello World programd starts, JVM creates the Main Thread and calls the program's main() method within same Thread. Also JVM creates other Thread internally to handle Garbage Collection activities. 

       Threads are used to run multiple task simultaneously and asynchronously under a single process. Threads are independent, concurrent paths of execution through a program, and each thread has its own stack own program counter and own local variables. Since each Threads will share same resources, its easy to share information's with each Threads. Just we need to take care on each Thread should not interfere with other threads in the same process.

       Using multi Threads are not easy in complex applications and programmers need to take on multiple Threads based on their business logic's. In Java we can implement Threads in 2 ways. First way by extending Thread class and other way by implementing Runnable interface. In this tutorial lets take a small example and we will discuss about both the ways in separately.


Example for extends Thread Class:



public class MyThreadClass extends Thread{
 
 public MyThreadClass() {}
 
 public MyThreadClass(String tName) {
  this.setName(tName); // Setting Thread name
 }
 
 @Override
 public void run() {
  System.out.println("Thread ::: "+this.getName() +" started");
  processMyThread();
  System.out.println("Thread ::: "+this.getName() +" Completed...");
 }
 
 private void processMyThread(){
  try {
   Thread.sleep(new Random().nextInt(1000));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}




public class ExtendThreadExample {
 public static void main(String[] args) {
  MyThreadClass obj1 = new MyThreadClass("Deposit");
  MyThreadClass obj2 = new MyThreadClass("Balance");
  MyThreadClass obj3 = new MyThreadClass("Withdraw");
  obj1.start();
  obj2.start();
  obj3.start();
 }
}




OUTPUT:



Thread ::: Balance started
Thread ::: Withdraw started
Thread ::: Deposit started
Thread ::: Withdraw Completed...
Thread ::: Deposit Completed...
Thread ::: Balance Completed...



       
        In above example we have used extending Thread class and we have Overrided run() method and we have given sample implementation. In 2nd class we have instantiated class for 3 times and we have pass Thread name for our identification.
       

       Once we complete 2nd type (implements Thread) we will discuss about which will be the best practice of using Threads in our application.


Example for implements Runnable interface:




public class MyThreadClass implements Runnable{
 
 public MyThreadClass() {}
 
 public void run() {
  System.out.println("Thread ::: "+Thread.currentThread().getName() +" started");
  processMyThread();
  System.out.println("Thread ::: "+Thread.currentThread().getName() +" Completed...");
 }
 
 private void processMyThread(){
  try {
   Thread.sleep(new Random().nextInt(1000));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}




public class ImplementsRunnableExample {
 public static void main(String[] args) {
  MyThreadClass obj = new MyThreadClass1();
  Thread t1 = new Thread(obj,"Deposit");
  Thread t2 = new Thread(obj,"Withdraw");
  Thread t3 = new Thread(obj,"Balance");
  t1.start();
  t2.start();
  t3.start();
 }
}



OUTPUT:



Thread ::: Deposit started
Thread ::: Withdraw started
Thread ::: Balance started
Thread ::: Deposit Completed...
Thread ::: Withdraw Completed...
Thread ::: Balance Completed...
 

Difference between Extending Thread and Implementing Runnable Interface:
 

  • By extending Thread class we are restricted that we can't extend other classes. Whereas while implementing Runnable interface we can extend other class also.
     
  • By extending we are inheriting complete Thread class into our class and we are Overriding only run() method. Whereas while implementing Runnable interface we are having our own implementation for run() method and just using Thread class by instantiating.
     
  • While extending Thread class we need to create multiple instance for our class, whereas in Runnable interface we can single class Object and can be passed to each Thread for its execution.

       Hence we can conclude that implementing Runnable interface will be best and hope you are cleat on the Java Threads. Still there are lot of important methods like wait(), notify(), notifyAll(), join(), yield(), sleep()  which we can discuss in our next tutorial.



 

Java 7 - Underscores in Numeric Literals

 
In this tutorial we will discuss about Underscore in Numberic feature added in Java 7. This is a nice and small feature which has added in Java 7 gives good readability for our codes. Its nothing but we can use underscores ( _ ) in-between numberic values in our code. Underscore can be added anywhere in the value part with few constraints listed below,

ALLOWED:
In-between 2 numbers or hexadecimal values or binary values are allowed. Below are the few valied literals by using underscore which are given in Oracle docs.

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

NOT ALLOWED:

Can't place underscore at beginning or end of the numberic value.
Adjacent to a decimal point in a floating point value literal is not allowed
Prior to an F or L suffix are not allowed
Positions where a string of digits is expected are not allowed
 

float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal point
float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point
long socialSecurityNumber1 = 999_99_9999_L;         // Invalid; cannot put underscores prior to an L suffix

int x1 = _52;            // This is an identifier, not a numeric literal
int x2 = 5_2;            // OK (decimal literal)
int x3 = 52_;            // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2;  // OK (decimal literal)

int x5 = 0_x52;        // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52;        // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2;        // OK (hexadecimal literal)
int x8 = 0x52_;        // Invalid; cannot put underscores at the end of a number

int x9 = 0_52;         // OK (octal literal)
int x10 = 05_2;       // OK (octal literal)
int x11 = 052_;       // Invalid; cannot put underscores at the end of a number
 

Lets see one small example by using underscore in numeric literals.
 



public class LiteralsExample {
   public static void main(String[] arg){
       
       float x1 = 52.4_5F;              
       float x2 = 5_2.12F;            
       
       int x3 = 52_3;              
       int x4 = 5_______2;        
       
       System.out.println("FLOAT VALUE :"+(x1+x2));
       System.out.println("INT VALUE   :"+(x3+x4));    
   }
}



OUTPUT:


FLOAT VALUE :104.57
INT VALUE   :575





Creating own ThreadPool using ThreadGruop

 
Welcome to this tutorial. In this tutorial we will discuss about creating our own ThreadPool by limiting no. of threads and pool size. We have 2 class called ThreadPoolTester and MyThreadPool where in ThreadPoolTester we are implementing the run() method and returning the Runabble instance.  Each instance are managed by other class called MyThreadPool which extends the ThreadGroup class. Below are those 2 classes sample code and sample output. 




public class ThreadPoolTester {

 public static void main(String[] args) {
  // Assign your no. of thread to create 
  int noOfProcess = 5; 
  // Assign your own thread pool size
  int poolMaxSize = 2;

  // Creating Threadpool with the thread size given above
  MyThreadPool threadPool = new MyThreadPool(poolMaxSize);
  // Creating threadpool Object
  ThreadPoolTester obj = new ThreadPoolTester();
  long time1 = getTime();

  for (int i = 0; i < noOfProcess; i++) {
   threadPool.process(obj.startProcess(i));
   
   /**
    * Just for showing threadpool not empty we have 
    * place this while loop and making thread to sleep 
    * In realtime while loop should not there, since it
    * will create performance issue. 
    */
   while (threadPool.getTaskListSize() >= poolMaxSize) {
    try {
     System.out.println("Threadpool NOT Empty           - " + threadPool.getTaskListSize());
     Thread.sleep(1000);
     System.out.println("Threadpool size after sleeping - " + threadPool.getTaskListSize());
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
  
  // Finally waiting for all thread to complete its process
  threadPool.join();
  long time2 = getTime();
  System.out.println("Time Taken ::: " + (time2 - time1) +" millisecond(s)");
 }

 private Runnable startProcess(final int taskID) {
  return new Runnable() {
   public void run() {
    System.out.println("Task " + taskID + ": start");
    
    // Putting each task to wait for random milli seconds
    try {
     Thread.sleep(new Random().nextInt(2000));
    } catch (InterruptedException ex) {
    }

    System.out.println("Task " + taskID + ": end");
   }
  };
 }

 public static long getTime() {
  Calendar currentDate = Calendar.getInstance();
  long time = currentDate.getTimeInMillis();
  return time;
 }
}




/**
 * Main ThreadPool class where we are extending ThreadGroup 
 * to implement our own pooling
 */
public class MyThreadPool extends ThreadGroup {
 private boolean active = false;
 private LinkedList<Runnable> qList = null;
 private int tId = 0;
 private static int tPoolID = 0;

 public MyThreadPool(int numThreads) {
  super("Pool - " + (tPoolID++));
  setDaemon(true);
  active = true;
  qList = new LinkedList<Runnable>();
  for (int i = 0; i < numThreads; i++) {
   new PooledThread().start();
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }

 public synchronized void process(Runnable task) {
  if (!active) {
   throw new IllegalStateException();
  }
  if (task != null) {
   qList.add(task);
   notify();
  }

 }

 protected synchronized Runnable getTask() throws InterruptedException {
  while (qList.size() == 0) {
   if (!active) {
    return null;
   }
   wait();
  }
  return (Runnable) qList.removeFirst();
 }

 protected int getTaskListSize() {
  return qList.size();
 }

 public synchronized void close() {
  if (active) {
   active = false;
   qList.clear();
   interrupt();
  }
 }

 public void join() {
  synchronized (this) {
   active = false;
   notifyAll();
  }
  Thread[] threads = new Thread[activeCount()];
  int count = enumerate(threads);
  for (int i = 0; i < count; i++) {
   try {
    threads[i].join();
   } catch (InterruptedException ex) {
   }
  }
 }

 private class PooledThread extends Thread {

  public PooledThread() {
   super(MyThreadPool.this, "Task -" + (tId++));
  }

  public void run() {
   while (!isInterrupted()) {
    Runnable process = null;
    try {
     process = getTask();
    } catch (InterruptedException ex) {}
    if (process == null) {
     return;
    }
    try {
     process.run();
    } catch (Throwable t) {
     uncaughtException(this, t);
    }
   }
  }
 }
}



OUTPUT:


Task 0: start
Threadpool NOT Empty           - 2
Task 1: start
Task 1: end
Task 2: start
Task 0: end
Threadpool size after sleeping - 0
Threadpool NOT Empty           - 2
Task 3: start
Task 3: end
Task 4: start
Threadpool size after sleeping - 0
Task 2: end
Task 4: end
Time Taken ::: 3285 millisecond(s)


Java 7 - Switch case with non-primitive (String)

 
In last tutorial we have discussed about multi-catch feature in Java 7. Now lets see how Java 7 supports non-primitive datatype in switch case. Until Java 6 we had only switch cases support for primitive datatypes like int, char, short, and byte.  

      Below small example will gives you how switch case works until Java 6 with primitive datatype int.



public class MySwitch {
 public static void main(String[] args) {
  int days = Integer.parseInt(args[0]);
  switch(days){
   case 0: 
    System.out.println("Monday");
    break;
   case 1: 
    System.out.println("Tuesday");
    break;
   case 2: 
    System.out.println("Wednesday");
    break;
   case 3: 
    System.out.println("Thursday");
    break;
   case 4: 
    System.out.println("Friday");
    break;
   case 5: 
    System.out.println("Saturday");
    break;
   case 6: 
    System.out.println("Sunday");
    break;
   default: 
    System.out.println("Sorry Invalid Input!!!");    
  }
 }
}


      In above program we have taken the command line input value and checked for day of week by using switch case. Here we have used primitive datatype int for variable "days".

      Additionally in Java 7 we have got non-primitive datatype String also can be used in the Switch case. Below example will give the same code of Java 7 Switch case with String.



public class MySwitch {
 public static void main(String[] args) {
  String day = args[0];
  
  switch(day.toLowerCase()){
   case "monday": 
    System.out.println("Hai its weeks 1st day...");
    break;
   case "tuesday": 
    System.out.println("Hai its weeks 2nd day...");
    break;
   case "wednesday": 
    System.out.println("Hai its weeks 3rd day...");
    break;
   case "thursday": 
    System.out.println("Hai its weeks 4th day...");
    break;
   case "friday": 
    System.out.println("Hai its weeks 5th day...");
    break;
   case "saturday": 
    System.out.println("Hai its weeks 6th day...");
    break;
   case "sunday": 
    System.out.println("Hai its weeks 7th day...");
    break;
   default: 
    System.out.println("Sorry Invalid Input!!!");    
  }
 }
}



Hope you are clear on new switch case in Java 7 and lets see other Java 7 feature in next tutorial. 






    

Java 7 new Exception Handling using multi-catch

 
Good to hear that in Java 7 has packed with lot of new features and additional features in Exception Handling, Switch case, Collections etc., Today we will discuss about the additional features which we have got from JAVA 7 in Exception handling. 

      Lot of programmers will use single catch() block for handling all exception types by placing the common Exception as like below in Java 6 and earlier versions. 



public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (Exception e) {
   // Log the exception 
  }
 }
}



      By handling exceptions like above we may lead to lot of issues like handling exceptions efficiently and also its not good practice until Java 6. So in earlier version we used to have multiple catch statements to handle each and every exceptions which may occur in the block as like below. 





public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (NullPointerException ex) {
   // Log the exception 
  }catch (ClassCastException ex) {
   // Log the exception
  }catch (StackOverflowError err) {
   // Log the error message
  }catch (Exception e) {
   // Log the exception
  }
 }
}


       
      Buy using like this also code goes ugly and lot of huddles in handling each and every Exceptions independently in separate catch blocks. 

     To over come this issue in Java 7 have packed with multi-catch feature in Exception handling and it will be handy to use in a single catch or multiple catch as programmers wish. Lets see small example as how to use multi-catch in Java 7 



public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (NullPointerException | ClassCastException | StackOverflowError ex) {
   // Log the exception 
  }
 }
}



Hope you are clear and happy that Java 7 has given a good feature for programmers to handle exceptions in a new way. Lets discuss more new features added in Java 7 in our next tutorial. 





How we can get the list of Key from HashMap?

Lets assume in interview you are been asked to list all the values in HashMap. HashMap contains around 1000 values and you have not given the list of keys to get the corresponding values. From HashMap to get the values first you need know the keys and later you can get the list of corresponding values.

            Today we will discuss about how to find the list of Key from HasMap. Before looking into direct program lets see some of the key features of HashMap and different between HashMap and HashTable. HashMap and HashTable will implements Map Interface but there are few difference between both of them where everyone needs to know.

HashMap is not synchronized where as HashTable is synchronized. If one who wants to use HashMap with synchronized then they the synchronize by using Java Collection utility as given below.
Since HashTable is synchronized by default it will slower than HashMap and performance wise HashMap will be better.
HashTable is defined in earlier version before Java Collections introduced.
HashMap will allow null key and value and where as in HashTable you cant place null key or value.
Iterator in HashMap is a fail-fast if any one tries to modify or remove the element from the HashMap and where as Enumeration in HashTable is not such. 
In HashMap value or key order will not be guarantee that will be same as inserted.

   

public class MyKeyList {
       
       public static void main(String[] args) {
               HashMap<String, String> hm = new MyKeyList().getHashMap();
                    
               Set<String> set = (Set<String>)hm.keySet();
               Iterator<String> itr = set.iterator();
               while(itr.hasNext()){
                       System.out.println(itr.next());
               }
               
               // Other way just by for loop as 
               for(Object key : hm.keySet()){
   System.out.println(hm.get(key));
  }

       }
       
       private HashMap<String, String> getHashMap(){
               HashMap<String, String> hm = new HashMap<String, String>();
               hm.put("one", "java");
               hm.put("four", ".NET");
               hm.put("two", "C");
               hm.put("five", "PHP");
               hm.put("three", "C++");
               return hm;
       }        
}


      In above program we have saved 5 values in HashMap and its been returned to main method and we have used Set and Iterator to get keys from the HashMap.
      Here need to remember about the function called ketSet() used to get the set of Keys from HashMap.



OUTPUT:



one
two
five
three
four



Hope you are clear now how to get list of Key from HashMap. You have any comments please drop it down.







How Java solves the problem of platform independent ?

In this tutorial we will discuss small information on how Java solves the problem of platform independent. Before seeing the solution as how its working we need to know answers for few questions like,

1. What is Java bytecode ?
2. What is machine code ?
3. What is JVM ?

Once we know about all these questions we can understand easily as how Java sloves this problem.

 

What is Java bytecode ?
 

      Each Java program which we write will be converted to bytecode by Java Compiler. From .java (Java program) to .class (Class file) file which contains byte codes. There are around 200 byte codes instructions which are used to covert any type of complex Java program to bytecodes files. Each byte codes instructions are of 8 bit which is 1 byte, hence its called Java bytecode.

What is Machine code?
 

     The lowest-level programming language is Machine languages and only the languages can understood by computers. Machine languages are impossible to understand by humans. Programmers will use high-level programming languages like (C, C++, Java, etc.,) are translated into machine language by a compiler. Every Operating System has its own unique machine language. Each high-level programs must be compiled to run on different types of computers.
For Example .exe file format is a machine language files where only Windows OS can understand and those files can't be executed in Mac or Linux etc.,


What id JVM?
 

     JVM is nothing but Java Virtual Machine. As the name indicates Virtual its not a real machine. Bytecodes compiled by compiler can be understand by any JVM and JVM used to convert the bytecode files to each machine code dependent files and executes the program. Where JVM are platform dependent and used to translate the bytecode into the machine language for a particular computer, and actually execute the corresponding machine-language instructions as well.

     Finally JVM are platform dependent and used to convert the byte code into corresponding platform machine languages. By this way Java solves the problem of platform independent.

Hope you are clear on how Java solves the platform independent problem.