Friday, 26 August 2016

Thread join

Join() method implementation

This method is use to join one thread at the end of another thread which means the join method waits for the currently running thread to stop executing until the thread it joins with complete the tasks
Syntax :
Try{
<Thread_object> .join()
}catch(InterruptedException e){}

Example:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package multithreadingtc;

/**
 *
 * @author shashank
 */

class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " remainder is i is " +i%10);
          
               Thread.yield();
           
        }
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.start();
        try
        {
            t.join();
        }catch(InterruptedException ex){}
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.start();
      
    }
   
}




Yield Method Implementation

Static Thread.yield() method implementation

This function is use to make current thread back to runnable state and to allow other threads of the same priority to execute .
Actually there is no guarantee that the yielding thread won’t just be chosen again all over the others

Example :-
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package multithreadingtc;

/**
 *
 * @author shashank
 */

class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=100;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " remainder is i is " +i%10);
          
               Thread.yield();
           
        }
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.setPriority(4);
        t.start();
        Thread t2 = new Thread(th);
        t2.setPriority(4);
        t2.setName(" third");
        t2.start();
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.setPriority(4);
        t1.start();
      
    }
   

}

Thread Priorities

Thread Priorities

Threads always run with some priority, that helps operating system to decide the order in which the threads are scheduled.
Java thread priorities lies between MIN_PRIORITY as a number 1 and MAX_PRIORITY as a number 10 and by default every thread has a priority of 5.
The scheduler uses preemptive, priority based scheduling mainly or time slicing scheduling to schedule the tasks
Preemptive, priority based Scheduling :- If a high priority thread enters into the runnable state than the high priority thread task executes until it  enters to wait/dead state or it will be bumped back to runnable if a higher priority task will came into existence.
Time Slicing Scheduling: - In this cases each thread is allocated a predefined slice of time and then it will sent back to runnable to give another thread a chance
Please note : Even if all threads are of equal priorities ,behavior is not guaranteed ,it means
1)      Scheduler can pick a thread to execute and run it until it enters to wait or dead state
2)      It can do time slicing to provide equal opportunities.

How to set a thread priority ?
Thread_object.setPriority(<int_value>);
Example:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package multithreadingtc;

/**
 *
 * @author shashank
 */

class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " remainder is i is " +i%10);
//            try
//            {
//                Thread.sleep(1000);
//            }catch(InterruptedException ex){}
        }
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.setPriority(8);
        t.start();
        Thread t2 = new Thread(th);
        t2.setPriority(6);
        t2.setName(" third");
        t2.start();
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.setPriority(4);
        t1.start();
      
    }
   

}

Thread Sleep Method

Sleep() method :-

The Sleep method is a static method of class Thread, we can use it to force thread to sleep mode before coming back to runabble
Try{
Thread.sleep(10*60*1000);
}catch(InterruptedException ex) {}

Example:

package multithreadingtc;

/**
 *
 * @author shashank
 */
class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=100;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " remainder is i is " +i%10);
            try
            {
                Thread.sleep(1000);
            }catch(InterruptedException ex){}
        }
    }
}
public class MultithreadingTC{
    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.start();
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.start();
        Thread t2 = new Thread(th);
        t2.setName(" third");
        t2.start();
    }   

}

Thread Scheduler states and Transitions

Thread Scheduler – States and Transitions

This article is in continuation of my previous article : Multithreading Introduction

Thread Scheduler:
It will decide which thread should run at any given moment and also takes out of the run state.
Any thread which is in runnable state can be chosen by the scheduler to be the only running thread and if a thread is not in runnable state it won’t be chosen to be the currently running thread.
However we have a runnable pool ,that when a thread has finished with its turn ,it moves to the end of line of runnable pool and wait util for its turn ,But still the order in which runnable threads are chosen is not guaranteed.
Methods that can influence thread scheduling:
Thread Class methods:
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int newPriority)
Object Class Methods :
Public final void wait()
Public final void notify()
Public final void notifyAll()

Thread states :
Since we know that it is the thread scheduler which move the threads from the running state back to runnable state, but there are other factors also which can change the state and can move  a thread from running state
For e.g :- run() once its completes , it will move thread from running to dead state
A thread can be only in one of the five states:

                                               New
                                                   |
                                             Runnable \
                                                |          Waiting/Blocking/sleeping
                                             Running /   
                                                      |
                                                Dead
                                               
                                                
1)  New State : Thread object has been created but start()       method has been not invoked yet, Any new thread begins its life cycle in the New state.
2)  Runnable : In this state thread is eligible to run ,But the schedule has not selected it to be the running thread , A thread first enters the runnable state which start() method is invoked, but it can also remain in runnable state after either running for coming back from a blocked , waiting or sleeping state.
3)  Running : The only way to get into the running state is that the scheduler chooses a thread from the running pool and start executing it.
4)  Waiting/blocking/Sleeping : These is a state where thread is not eligible to run in order words we can say that it is not runnable but return to a runnable state later.

5)  Dead– A thread is considered to be dead once its run method is completed

Thursday, 25 August 2016

Factory Pattern

                                                            Factory Patterns


It is one of the most commonly used design pattern, it comes under creational patterns where we will create objects while hiding the internal logic.

In such type of designs we will create a separate class /factory to generate objects of concrete class based on supplied details

Let us suppose we need to create a design for Robot industries.

We have a contract to design a software for XYZRobot ltd , As per the initial requirements these people want us to design robots which must be different in design and appearance.

Based on such initial requirement we came up with a design prototype taking three types of designs into consideration

1)      RobotsLikeHuman

2)      RobotsLikeAnimal

3)      RobotsLikeMachine

Here in this design

  1. We are going to create a Robot interface and concrete classes(RobotsLikeHuman,RobotsLikeAnimal,RobotsLikeMachine) will implement this interface.
  2.  We will create a factory class which will generate objects known to be as RobotFactory.
  3.  We will create RobotPrototype class which will use RobotFactory class to get a Robot object based on its type as needed.





                                                  XYZRobot.ltd Design

Example:

/*
 @author -- shashank
 */
package robotprototype;
 interface Robot
{
    public void design();
}
class RobotLikeHuman implements Robot
{
    public void design()
    {
        System.out.println("I am a Human");
    }
}
class RobotLikeAnimal implements Robot
{
    public void design()
    {
        System.out.println("I am an Animal");
    }
}
class RobotLikeMachine implements Robot
{
    public void design()
    {
        System.out.println("I am a Machine");
    }
}

class Robotfactory
{
    public Robot getdesign(String designtype)
    {
        if(designtype=="HUMAN")
        {
            return new RobotLikeHuman();
        }
        else if(designtype=="MACHINE")
        {
            return new RobotLikeMachine();
        }
        else if(designtype=="ANIMAL")
        {
            return new RobotLikeAnimal();
        }
        return null;
       
    }
}

public class RobotPrototype {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        Robotfactory rf = new Robotfactory();
       
        Robot r = rf.getdesign("HUMAN");
        r.design();
       
        Robot ra = rf.getdesign("ANIMAL");
        ra.design();
       
       
        Robot rm = rf.getdesign("MACHINE");
        rm.design();
        // TODO code application logic here
    }
   
}

Design Patterns Introduction

                  Design Patterns

Introduction:
Mistakes are meant for learning not repeating and wise man learns from the experience of others.
Based on such mistakes/experiences software developers had design the solutions for general problems. It represents best practices which should be use by software developers while designing a solution.

Initially it is based on below principles of object oriented design but later it has been evolved over a long period of time

1)      Object composition over inheritance
2)      Program to an interface not an implementation

Why should we use design patterns?

1)      It will provide common standard terminology to all software developers.
2)      It helps software developers to learn design in a easy way

Design patterns are broadly classified under below categories

1)      Creational Patterns: These patterns are used to create objects while hiding the internal logic which gives a program more flexibility to decide which object needs to be materialized at given instance.

2)      Structural Patterns:  These patterns focus on class and object compositions.

3)      Behavioral Patterns : These are design to focus on communication between objects.


We will look into all these type of patterns closely  in next articles:

Wednesday, 24 August 2016

Multi Threading Introduction

Multi Threading

A thread is a light-weight smallest process that can run concurrently with the other threads of the same process and has its own call stack. Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a process share the common memory. The process of executing multiple threads simultaneously is known as multithreading.
In Java there is one thread per call Stack , Even if we don’t create threads in our program, threads are running in background.

Since we know that the whole execution starts from main() method, so that main() method run in one thread known as main thread, If we look main call stack trace, we can see that main() is the first method on the stack , but as soon as we create a new thread , a new stack created and method called from that thread run in a call stack that is different from main() call stack.

A very nice quote about thread :

When it comes to threads  , a very little is guaranteed
                                                                                    --- Kathy Sierra

Difference between Multitasking – Multithreading  - Multiprocessing - Parallel Processing.

I have seen people are often confused between below mentioned terms.

Multitasking: Ability to execute more than one task at the same time is known as multitasking.
Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.
Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.
Creation of a Thread
A thread in java begins as an instance of java.lang.Thread. Lets have a look at these methods of Thread class.
  • start() – Start a thread by calling its run method.
  • run() – Entry point of thread i.e the action happens in the run() methods, you always write the code that needs to be run in a separate thread in a run() method. The run method will call other methods
  • getName(): It is used for Obtaining a thread’s name
  • SetName(): It is used set a thread’s name.
  •  getPriority(): Obtain a thread’s priority.
  •   isAlive(): Determine if a thread is still running
  •   join(): One Thread join into the end of another thread and it will wait for a current dependent thread to terminate
  • Sleep(): suspend a thread for a period of time
  •  Yield() : Cause a thread to go from  running to runnable
  • getId(): This Method return a positive, unique, long number and that number will be thread’s only number for the thread’s entire life.



There are two ways to create a thread in java
Ø Extending Thread class
Ø Implementing Runnable Interface
Please Note: Every thread of execution begins as an instance of Thread class.
Regardless of whether you run() method in a Thread subclass or a Runnable implementation class
n  A new thread of execution starts(with a new call stack)
n  The thread moves from the new state to the runnable state.
n  When a thread gets a chance to execute , it targets run() menthod

Example : - Extending Thread class
Example 1 :
package multithreadingtc;
/**
 *
 * @author shashank
 */
public class MultithreadingTC extends Thread{

    public void run()
    {
        System.out.println("Execution starts here");
    }
    public static void main(String[] args) {
        // TODO code application logic here
        MultithreadingTC th = new MultithreadingTC();
        th.start();
}
}



Example 2 :
package multithreadingtc;
/**
 *
 * @author shashank
 */
class Multithreading extends Thread
{
   public void run()
    {
        System.out.println("Execution starts here");
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        th.start();
    }
   
}
Example implementing Runnable Interface
Example 1:
package multithreadingrunnable;
/**
 *
 * @author shashank
 */
class Multithreading implements Runnable
{
     public void run()
    {
        System.out.println("Execution starts here");
    }
}
public class MultithreadingTC{
    public static void main(String[] args) {
        Multithreading th = new Multithreading();// Instantiate Runnable class
        Thread t = new Thread(th);// Pass your runnable instance to the Thread
        t.start();
    }
}
Example : Running multiple threads
package multithreadingtc;

/**
 *
 * @author shashank
 */

class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=3;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " value of i is " +i);
        }
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.start();
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.start();
        Thread t2 = new Thread(th);
        t2.setName(" third");
        t2.start();
    }
   


}

Please follow my next article over Thread States/Transitions/Scheduling and Synchronization.