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.



      Friday, 9 May 2014

      ADF Video Tutorials by Oracle

      References:

      ADF Video tutorials provided by Oracle.

      Also  we can find Oracle's  ADFInsiderEssentials

      we can found number of tutorials with good explanation and examples 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.....

      01_EJB_Introduction_TO_EJB

      EJB

      • EJB stands for Enterprise Java beans.
      • This will come into service layer in the J2EE architecture where all of our business logic reside.
      • For example business operations like manupulating database,sending mails,sending messages to message queues.
      •  J2EE container Provides some facilities to EJB like Transaction,security,pooling,concurrency,Timers,Intersepters..

      Types of EJBS


      1.Stateless Session Bean
      • The container usually maintains a pool of instances of beans.
      • When a client invoke the method of bean  first one instance may picked up by the container and one more time the client trying to access the other method  in the bean may be some other instance invoked by the container.So first instance may not aware of the values of other instance of the same bean.So we cant store state info in this case.

      • We should not save the State in this bean.Means we cant store any values for the variables and state information  like 
                                     @stateless
                                     Public String getHello( String Name){
                                     String EmpName=Name; //We cant store like values
                                     }

      • Most of the business operations are singular.Like sending Mails and logging in user..They dont want to store the state of information.In such cases we may use Stateless session bean.
       In this type of beans the container managed the pool of instances.
      .
      2.Stateful Session Bean


      • This beans are Client oriented.There is one instance of bean for each client.
      • If a client invoke a method of bean one instance get created and the client will invoke another method of the bean  and save some state and second time the perticular instance only get picked up for the specific client.So it will maintain the state information.
      • There is no pool of instances of the bean in the container,the instance is created just before the client get serviced.
       




      • The client is supposed to issue the command in this type of bean.But in stateless session bean container will maintain the instances.



      3.singleton Session Bean
      • Only one instance this bean per application server.Every client will invoke the same instace anyway some concurrency mechanisms are there to avoid conflicts.
      • If we have 2 JVMs in our server it will create two singleton instances per each JVM.Also in distributed systems environment we have different JVMs and this sigleton bean will create each instance per each JVM:)



      Note:

      Clients:


      Lets  assume one bean in service layer(EJB).This bean may be accessed  by  another bean(another EJB) in the same layer or  in web layer(using JSP or JSF) or some other layer with the same container or from  outside..

      Local:Beans reside within application server.
      Remote:When beans reside outside the Application server known as Remote clients.

      What's New in J2EE 7

      Java EE 7 is the latest edition of the enterprise platform that powers a lot of (web) applications.

      Top Features of J2EE 7 


      1. Batch Applications
      2. Web Socket
      3. JSON Processing
      4. More Annotated POJOS
      5. concurrency Utilities

      New Releases of J2EE  7 technologies

      1. HTML 5
      2. JAX-RS 2.0   (Java API for Restful(RePresentational State Transfer) Webservices)
      3. JMS 2.0
      4. JPA 2.1   (Java Persistance API)
      5. JSF 2.2    (Java Server Faces)
      6. Expression Language 3.0
      7. CDI 1.1   (Contexts and Dependency Injection)
      8. EJB 3.2  (Enterprise Java Beans)
      9. Batch Application for Java Platform 1.0
      10. Concurrency Utilities for J2EE
      11. Servlet 3.1
      12. Bean Validation 1.1
      13. Java Mail 1.5
      14. JCA 1.7  (J2EE Connector Architecture)
      15. Java API for Web socket 1.0
      16. JTA 1.2   (Java Transaction API)
      17. Java API for JSON Processing 1.0 (Java Script Object Notation)
                                      
                                       

            

      Tuesday, 6 May 2014

      Working_with_JMS_Artifacts


      Please refer introduction.

      JMS Artifacts

        To work with any JMS Application we need to first create the following artifacts in Weblogic console.(Install and run weblogic server if you are not install yet/ Run Integrated weblogic server which are working with).

      • JMS Server
      • JMS Module
      • JMS Subdeployment
      • JMS ConnectionFactory
      • JMS Queue/JMS Topic(These are the destinations we need to create  Based on our Requirement..see introduction).

      Creating JMS Artifacts in Weblogic console
      • Login to Weblogic Console."http://localhost:7001/console".




      JMS Server
      •  Click on Services-->Messenging-->JMS Servers.


      • Click on New To Create new JMS Server.
      • Enter any Name for JMS server and click next.


      • NextScreen,Select Target as Admin server and click finish.
      • Observe that JMS server created successfully and your server name in the list of JMS servers

      JMS Module


      • From Weblogic console Home page click on JMS Module.

      • Click on New to create New JMS Module.
      • Enter any name for JMS Module and Click next.


      • Select Target as Admin server and Click next.
      • Select the Check box to add our resources to JMS Module and click Finish.
      • It will navigate to JMS Module Configuration Page.Go to Subdeployments tab,To create New Sub deployment to our JMS Resources.And Click on New.
      • Enter any Name for Subdeployment and click next.


      • Select your JMS Server which we have created earlier as targets and click Finish.(dont select admin server)

      • Make sure that your subdeployment created for the JMS Module.



      JMS ConnectionFactory

      • JMS Modules-->click on your JMS Module-->Configuration Tab,click on New To create JMS Resources.

      •  First Select Connection Factory Radio button and click next.


      • Enter any Name and JNDI Name for Connection factory as follows.We will use this Jndi name in our Application while working with JMS.Click Next.



      • Click on Advance Targeting to Point our Subdeployment which we have created earlier.




      • Click Finish.

      JMS Queue

      • Like Connection factory we need to Create JMS Destination (Here JMS Queue) as follows.



      • In the Resources select Queue and click next..ENter any name For JMS Queue and JNDI name for it..We will use this JNDI name while sending messages to JMS Queue in our Application.

      • Click Next.Select our subdeployment and click Finish.
      JMS Topic

      • Create JMS Topic.

      • Enter JMS Topic and JNDI Name.

      • select the Subdeployment and click finish.


      • Done...
      Now we are ready to work with JMS Application to send and recieve messages from JMS Queue/Topic when two different applications wants to communicate with each other.

      sample Application will update soon..

      01_JMS_Introduction to JMS

      JMS
      • JMS stands for Java Message Service.
      • JMS is a standard API for accessing enterprise messaging systems. Specifically, JMS:
      •  Enables Java applications sharing a messaging system to exchange messages
      •  Simplifies application development by providing a standard interface for creating, sending, and receiving messages.

      Example:

            If we have two Applications Like Application A and Application B.
      • case 1:If the above two applications belongs to two different companies which are trying to communicate.
      • case 2:If the two applications are from Different depatments in the same company
      • case 3:If one application is developed in JAVA  and other is developed in other technology
      How the two applications are communicate with each other????


      By using JMS Provider those two applications are communicated with each other by sending messages to one another as shown in the following diagram.
      • Messages that are exchanged through JMS PRovider.JMS Provider is also known as Message server,Message Broker,MOM(Message Oriented Middleware).
      • The Application which sends a message to JMS Provier is known as Message Producer where as which recieves the message is known as Message Consumer.
      • Message consumer/producer and what ever is intereact with JMS Provider is known as JMS client.

      JMS Provider

      • With in JMS Provider we can create JMS destinations known as Queues and Topics.
      • So the Message Producer can send message to a perticular destination(Queue/Topic) and Consumer can recieve message from a perticular Destination(Queue/Topic).


      • A destination can have more than one producer/consumer.The main advantage of JMS architecture is like loosely coupled means the producer doent know who is going to  recieve the message and the consumer doesnt know who will send the message. 


      JMS Messaging Models

       we have two types of JMS Messeging models.

      1. Publish and subscribe Model
      2. Point To Point Model


      1.Publish and Subscribe Model

      • In this model Message Producer is known as  Publisher and the Message Consumer is known as Subscriber.
      • The destination we will use in this model is known as Topic.
      • so when the Producer sends the message it will deliver to multiple subscribers as shown in the following figure.

      2.Point To Point Model(P2P model)

      • In this model Message Producer is known as sender and  message Consumer is known as Reciever.
      • The destination we will use in this model is Queue.
      • so When the producer sends the message to the queue only a perticular reciever will going to be recieve the message even though we may register number of recievers as shown in the figure.


      Please refer JMS example..

      Reference:Ashiraj series..