Monday, 12 May 2014

Creating Threads in JAVA

Introduction to multithreading

Thread Creation

We can Create threads in Java by using the following two ways.
  1. By Extending Java.lang.Thread class.
  2. By implementing the Java.lang.Runnable interface.
  1. Create thread by extending Thread class
  • The class should extend Java Thread class.
  • The class should override the run() method.
  • The functionality that is expected by the Thread to be executed is written in the run() method.
Example:

class MyThread  Extends  Thread{
          Public Void run(){
     system.out.println("thread started running.....");
                                   }
}


class MyThreadDemo{
       
             Public Static void main(String srgs[]){
                            MyThread obj=new MyThread();
                               obj.start();
                           }
}


2.Create Thread by implementing Runnable interface



    • Other way of creating a thread is to create a class that implements the Runnable interface. We must need to give the definition of run() method.This run method is the entry point for the thread and thread will be alive till run method finishes its execution.
    • Once the thread is created it will start running when start() method gets called. Basicallystart() method calls run() method implicitly.

      Example:

      class MyThread  implements Runnable{
                Public Void run(){
           system.out.println("thread started running.....");
                                         }
      }

      class MyThreadDemo{
           
                   Public Static void main(String srgs[]){
                                  MyThread obj=new MyThread();
                                    Thread t1=new Thread(obj);
                                     t1.start();
                                 }
      }

      Multi-threading in Java


      Thread??

      • Multi-tasking allows multiple programs to be run at the "same" time. Lets visualize this as  each application as running on its own processor.

                        






      • Just like programs can run concurrently, pieces of the same program can run concurrently. This ability is known as Threading.
      Example:

      •  Lets consider a very simple example.Lets assume that we have an array of 10000 like

                              Array a[10000];

      •  Here our task is to add all the array element values.so generally we use some thing like
                          for(i=0;i<10000;i++){
                                  sum=sum+sum[i];
                                 }
      •  So by adding all the 10000 values by single process(or like by one person) it will take lot of time to do this.
      • Instead of doing this as a single program ,Lets divide this tasks among 10 persons as 10 pieces of tasks(threads)like
                          person1  =add a[1]      to a[1000]--->thread 1
                          person2  =add a[1001] to  a[2000]--->thread2
                           .........
                          person10=add a[9001]  toa[10000]-->thread 10
      • Lets allow all these 10 multiple  threads run concurrently.So we will save time and work load of single program by performing multithreading.

      Multithreading in java

      Java multithreading allows you to do multiple tasks at the same time.
      • Every java program creates at least one thread [ main() thread ]. we can create additional threads whenever needed.
      • In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time.
      • Threads are lightweight processes; they share the same address space. In Multithreaded environment, programs make maximum use of CPU so that the idle time can be kept to minimum.
      • There are several thread states, A thread can be in any one of the state at a particular point of time. It can be running state. It can be ready to run state as soon as it gets CPU time. A running thread can be suspended. A suspended thread can be resumed. A thread can be blocked when waiting for a resource. At any time a thread can be terminated.

      Whats the need of a thread or why we use Threads?

      • To perform asynchronous or background processing
      • Increases the responsiveness of GUI applications
      • Take advantage of multiprocessor systems
      • Simplify program logic when there are multiple independent entities


      What happens when a thread is invoked?


      When a thread is invoked, there will be two paths of execution. One path will execute the thread and the other path will follow the statement after the thread invocation. There will be a separate stack and memory space for each thread.


      Thread Lifecycle



      1. New state : After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
         
      2. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 
      3. Timed waiting is a thread state for a thread waiting with a specified waiting time. 
      4. waiting state due to the calling one of the following methods without     timeout:Object.wait() or Thread.join()
      5. blocked : A thread can enter in this state because of waiting the resources that are hold by another thread.
      6. After thread has completed execution of run() method, it is moved into terminated /Dead state . If any thread comes on this state that means it cannot ever run again.
      Note, that thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate. It means that waiting state could be made a composite state with states corresponding to these specific conditions.
      Methods to Manage Threads:
      • getName()     :This is used to obtaining Thread's Name.
      • setName()      :To give thread a name.
      • getPriority()    :Obtains a thread Priority.
      • isAlive()         :Determine If the thread is still running.
      • join()             :Wait for a thread to terminate.
      • run()              :Entry point for the thread.
      • sleep()           :suspend a thread for a period of time.
      • start()            :Start a thread by calling its run() method.
      • notify()           :This wakes up threads that called wait() on the              same object and moves the thread to ready state.
      • notifyAll()     :This wakes up all the threads that called wait() on the same object.
      • Yield()            :It is used to give the other threads of the same Priority a chance to execute i.e.causes current running thread to move to reunnable State.
      • Stop()        :The stop() method is used to stop the execution of a thread before its run() method terminates.

      To know how to create threads..please click here.



      Wednesday, 7 May 2014

      What's New JAVA 8 Release

      JAVA 8

      “Java Platform, Standard Edition 8 (Java SE 8)” is released on 18th March 2014. Along with the Java SE 8 platform, the product that implements the platform, “Java SE Development Kit 8 (JDK 8)”

      Java SE 8 is one of the most feature packed release in the JavaHistory.

      Highlight Features in Java 8 Release:)
      • Permanent Generation
      • Parallel Array Sorting
      • Lambda Expressions
      • Optional Class API
      • Date & Time API
      • Functional Interfaces
      • Pipelines and Streams
      • Type Annotations
      • Default Methods

      1.Permanent Generation
                What does it mean??
      • who has never configured their "PermSize" or their "MaxPermSize" JVM memory?
      • This was normally done after receiving those ugly "java.lang.OutOfMemoryError:PermGen error" errors.
      • This is now replaced by Metaspace in this release.The Metaspace will re-size itself depending on the demand we have of memory at runtime.If we need to,we can still tune the amount of Metaspace by setting "MaxMetaSpaceSize" param.
      2.Parallel Array Sorting
               We are used to sorting arrays with “Arrays.sort”. This used Merge Sort or Tim Sort algorithms for the sorting. The problem they have is that they are executed sequentially, so we do not gain all the benefits multithreading has to offer us. For this purpose they implemented “Arrays.parallelSort”.

      3.Lambda expressions

      • Lambda expressions might be the biggest and most anticipated feature of Java 8. They are basically used to pass code instead of objects to a method or to deal with group of data to execute algorithms.
      • This will produce much simpler and more readable code. Lets take a look at some concepts around this.
      • The normal approach in Java is to iterate collections externally, so we would have something like this:
      for (String value: myCollection) {
                      System.out.println(value);
              }
      • syntax for Lambda expressions:
                       input arguments -> body
      • What we are doing here is iterating the list and pulling objects one by one. It would be more natural if we could just say from the beginning what we want to extract form the collection. This is exactly the concept of how we would do it with lambdas:
            myCollection.forEach((String value) -> System.out.println(value));

      4.Optional Class API

      Why?
      • Every Java programmer is maddened every once in a while by the notorious NullPointerException. Not only Java programmers, by the way. Probably every JVM programmer is suffering from the problem.

      NULL??
      • In Java null is actually a type, a special one: it has no name, we cannot declare variables of its type, or cast any variables to it, in fact there is a single value that can be associated with it (i.e. the literal null), and unlike any other types in Java, a null reference can be safely assigned to any other reference types.

      what??
      The newer version of Java i.e Java 8 introduces a new class called Optional. The Javadoc for Optional class says:Optional class is supposed to cure NullPointerExceptions


      A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.


      All features and samples will update soon.....

      Thursday, 24 April 2014

      Factory Design Pattern

      What??

      • In this,we create object without exposing the creation logic to the client and refer to the newly created object using common interface 
      • At run time ,we get the object of the type based on the parameter we pass.
      • Actually we use this Factory design pattern in the situation like,If we have a super class and subclasses and based on the data provided we have to return the object of one of the subclasses.


      will update soon.........

      Wednesday, 23 April 2014

      Java Design Patterns Links Page



      1. Singleton
      2. Factory
      3. AbstractFactory
      4. Builder
      5. Prototype
      6. Adapter
      7. Composite
      8. Proxy
      9. Fly Weight
      10. Facade
      11. Bridge
      12. Decorator
      13. Template Method
      14. Mediator
      15. Chain Of Responsibility
      16. Observer
      17. Strategy
      18. Command
      19. State
      20. Visitor
      21. Iterator
      22. Interpreter
      23. Memento

      Singleton Design Pattern

      Singleton Design Pattern

      When?
      • Sometimes it's appropriate to have exactly one instance of a class and provide a global point of access to it.
      • EX:Lets Assume that there is a product store and It would like to maintain the products of their store in a List.We dont know how many stores access this list and update the list details.In this case,if we create multiple instances if store A update one instance,Store B doest not know the new list if it  access another instance of this class.So to avoid this,we will create only one instance and allow all the stores access the same one instance.
      • Note:In this Pattern only one instance is created in  entire JVM for this class.If we have in distributed system ,for every JVM container there will be one instance.If we have two JVMs in our machine, we have 2 instances per each JVM.

      How??

      step1:  Create a class and restrict the class as no body can access the class.To do this Mark the constructor as Private.

                  public class SingletonDemo {
      private SingletonDemo () {}
      }

      step2:As we mark the constructor as private ,No other class create a instance of this class.So We need to create a instance of this class and write a method to return the instance.Mark this method as static.so that other classes can access this method.


       public class SingletonDemo {

               private static SingletonDemo instance = null;
      private SingletonDemo () {}

      public static SingletonDemo getInstance() {
                          
                      if (instance == null) {
                          instance = new SingletonDemo();
                      }
                          
              return instance;
          }
      }
      
      
      
      
      Done....
      
      
      
      
      Note:This simple singleton pattern is not working in multithread environment.Assume that two thread are actually call this method at a time it will call the if block and create two instances (prob)
      
      
      Solution:Mark themethod as synchronized 

      Tuesday, 22 April 2014

      JAVA Design Patterns Categories Introduction

      Creational Design Patterns:
      This patterns are used in Class instantiation.

      • How to Creates objects Effectively.
      • How we can Reuse the objects effectivly.
      More:
             object pool design pattern


      Structural Design Patterns:
            These patters are all about class and object composition.
      • How objects and classes form a combine a larger structures.
      • Identifying a simple way to realize relationships between entities.
      More:
        Private class Data Pattern
        Front controller pattern
        Module  Pattern

      Behavioural Design Patterns:
      • How two objects communicate with each other.
      • Interaction between objects is loosely coupled.
      • How objects interact and How the classes/objects sends messages to talk each other in order to accomplish some functionality.
      More:
             null Object  design Pattern


      JAVA Design Patterns

      WHAT:

             Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development.
      A DESIGN PATTERN IS A WELL DESCRIBED SOLUTION TO A COMMON SOFTWARE PROBLEM.

      WHY:
      Design Pattern describes:
      • Each Design Pattern describes a problem in development and in which situation the problem occurs.
      • It also Describes Why this Problem occur
      • Provides solutions for every Problem.
      • We can use this solution many times.
      • Describes when to use this design patterns and what are the consequences.

      Design Patterns have the follwing main usages in software development.

      1. Design Patterns are already defined and provides industry standard approach to solve a recurring problem, so it saves time if we sensibly use the design pattern.
      2. Using design patterns promotes reusability that leads to more robust and highly maintainable code. It helps in reducing total cost of ownership (TCO) of the software product.
      3. Since design patterns are already defined, it makes our code easy to understand and debug. It leads to faster development and new members of team understand it easily.
      We Have  mainly 23 Design patterns in Java and Categorized into 3 types.

                    
             To see  Categories design patterns explanation click here