Tuesday, February 21, 2017

Daemon Thread

Following characteristics defines the daemon threads:
  1. Daemon threads are service provider threads, they provide services to other threads.
  2. These threads dead automatically if the thread to which they are providing service are dead.
  3. These threads never show any output.
  4. They always run in background.

For example assume a scenario where a client side thread needs to display an image, now here some should be there who brings the image from server / database. So, in this case just create a server side daemon thread which will bring image from the server database.
A real example if daemon thread is relay fielding in cricket match, where one man throws the ball to another and he it throws further.

Java’s garbage collector thread is a daemon thread.

There is a method setDaemon(Boolean) to make a thread as a daemon thread.
For example:

package dev21century.threading;
class DThread1 extends Thread
{     
       DThread1(String threadName)
       {
              super(threadName);
       }
       public void run()
       {
         for(int i = 0;i<5;i++)
          {
           System.out.println("Thread Name: " + getName());
          }
       }
}

public class MainThread {

       public static void main(String[] args) {

        DThread1 dthread1 = new DThread1("DaemonThread1");
       
        dthread1.setDaemon(true);
        //marking this thread as a daemon thread
       
        dthread1.start();
            
        for(int i = 0;i<4;i++)
        {
          System.out.println(Thread.currentThread().getName());
        }            
     }

}

Output:
main
Thread Name: DaemonThread1
main
Thread Name: DaemonThread1
main
main
Thread Name: DaemonThread1
Thread Name: DaemonThread1
Thread Name: DaemonThread1

Try to run this program many times the output may be different.


Monday, February 20, 2017

ThreadGroup In Java

ThreagGroup is a class in java which is used to group the set of threads. In this way we can perform a common type of tasks to all threads at one shot like interrupting them all.
As a real example providing training to multiple students one by one for same course is not advisable, instead group them up and teach them in a class room only once.

Example:
package dev21century.threading;
//thread 1 class
class GThread1 implements Runnable
{
       //run method is the main code of thread
       public void run()
       {
         for(int i = 0;i<5;i++)
          {
           System.out.println("Thread Name: " + Thread.currentThread().getName());
          }
       }
}
//thread 2 class
class GThread2 implements Runnable
{
       public void run()
       {
        for(int i = 0;i<7;i++)
         {
          System.out.println("Thread Name: " + Thread.currentThread().getName());
         }
       }
}

//thread 3 class
class GThread3 implements Runnable
{
       public void run()
       {
        for(int i = 0;i<9;i++)
         {
          System.out.println("Thread Name: " + Thread.currentThread().getName());
         }
       }
}

public class MainThread {

       public static void main(String[] args) {

        ThreadGroup threadGroup = new ThreadGroup("MyThreadGroup");

        Thread gthread1 = new Thread(threadGroup, new GThread1());
        Thread gthread2 = new Thread(threadGroup, new GThread2());
        Thread gthread3 = new Thread(threadGroup, new GThread3());
       
        threadGroup.interrupt();
        /*with this statement, all 3 threads will
        be interrupetd at once.*/
       
        gthread1.start();
        gthread2.start();
        gthread3.start();

        for(int i = 0;i<11;i++)
        {
          System.out.println(Thread.currentThread().getName());
        }            
     }

}

Output:
main
main
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
Thread Name: Thread-0
main
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
Thread Name: Thread-0
main
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
main
main
main
Thread Name: Thread-0
main
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-0
Thread Name: Thread-0


Constructor in Inheritance

Constructor plays an important role in inheritance, constructor overriding is allowed in java. There are a set of rules and regulations while implementation constructor in inheritance. Let’s take this example:

Create a file A.java:

class A
{
      A()
      {
            System.out.println("Constructor A");
      }
}
class B extends A
{
      B()
      {
            System.out.println("Constructor B");
      }
}
public class C extends B
{

      C()
      {
            System.out.println("Constructor C");
      }

      C(int x)
      {
            System.out.println("Parameterized Constructor C - " + x);
      }

      public static void main(String[] args)
      {
            new C();          //this is Anonymous object (Will discuss later)
            new C(10);
      }
}

Output:



Rule 1:
Whenever a child class constructor is executed, it has to execute the immediate parent class constructor first, then itself. If for any reason the child class is not able to execute its parent’s constructor then it cannot execute its own constructor.
In this example class A’s constructor will execute Object class constructor.
If we do not extend a class then it implicitly extend Object class.
Quick Question – why it is required to execute parent class constructor first? How it is implemented internally.

Answer – because child class does have ability to inherit all of their data members and methods but not the constructors. For example, if we have written database connection code in B class constructor, then we can never get it explicitly from C class constructor, and all database connection code will be required to be re written in C class constructor. This rule is defined for reuse of constructor.

We can call the super class constructor explicitly using super keyword, but it should be the first line in any constructor. In above example compiler automatically add super keyword in each constructor. Like this:

      C()
      {
            super()
            System.out.println("Constructor C");
      }

      C(int x)
      {
            super(); 
            /*in this case B must have a constructor with int
            argument otherwise compiler error */
            System.out.println("Parameterized Constructor C - " + x);
      }

Rule 2:
Compiler always adds a default constructor in each class if no any constructor is kwritten in it. In case a parameterized constructor is defined in parent class and child class is defining default constructor this compiler will throw error as it will be unable to find default constructor in parent class.
For example:

class B
{
      B(int x)
      {
            System.out.println("Constructor B");
      }
}
public class C extends B
{

      C()
      {
            super();  //Line No 13
            System.out.println("Constructor C");
      }

      public static void main(String[] args)
      {
            new C();
            new C(10);
      }
}

Compiler will give following error at line No 13 in above program:
Error: The constructor B() is undefined

We can resolve above issue by either adding a default constructor in class B or by replacing super() with super wih an int argument in class C constructor.


Advantages of inheritance

  1. Reusability – by reusing the fields or methods we save the wastage of memory. In our example we need not to declare supplierName, supploerAddress & supplierContact 2 times in XYZLimited & ABCLimited. This is the beauty of inheritance.
  2. Reduced complexity of code.
  3. Dynamic binding can be achieved using inheritance.


Characteristics of inheritance


  1. A private data member or method cannot be inherited by sub class. However if there is a public method in parent class which further access its private members then such methods can be directly used from its child class.
  2. Only protected and public members can be inherited.
  3. A class cannot have more than one parent class, in short multiple inheritance is not allowed in java. (Available in C++). However we can achieve indirectly using "interface" concept which we will discuss in detail in next to next chapter.
  4. Parent class can always store reference of its child class but vice versa is not possible.
  5. e.g.
    Supplier supplier1 = newSupplier();             //Correct
    Supplier supplier2 = newXYZLimited ();          //Correct
    XYZLimited xyzSupplier1 = newXYZLimited();      //Correct
           XYZLimited xyzSupplier2 = newSupplier();        //Incorrect
  6. In sub class the inherited members can be used directly just like its local members.
  7. We can declare a field in sub class with same name as declared in super class, but this is not recommended.
  8. We can declare new fields in sub class which are not in super class (e.g. cubicalSize in above example).
  9. We can write a new instance method in sub class with same signature (return type, name, parameters) as the one in super class, this process is known as method overriding.
  10. A sub class constructor can call super class constructor using “super” keyword.
  11. A nested class inside parent class has access to all private members (field & methods), and if that nested class is either public or protected then the child class can access it directly, thus the private members are accessed indirectly through inner class of parent. We will discuss about nested class in later chapters.