what is Ajax, Why use Ajax and How to implement in Java


Some use for Ajax interactions are following:

1. Real time form data validation
e.g. UserID, EmailID, Serial No, Postal Code etc.
2. Load on demand
e.g. fetch data in background, allowing browser load page quickly
3. Sophisticated user interface controls and effects
e.g. control such as calendar, trees, menus, data tables ,rich text editor.
4. Refreshing data and server path
e.g. such as scores, stock quotes, weather, or application specific data.
5. Partial submit
6. Page as an application
e.g. single page application that look and feels like desktop application.

XMLHttpRequest:

A JavaScript object, it allow client-side script to perform HTTP Request, and it will parse an xml server response. Ajax stands for asynchronous; when you send that HTTP request you don’t want the browser to hand around waiting for the server to respond. Instead, you want to continue reading to the user’s interaction with the page and deal with the server’s response when it eventually arrives. To accomplish this, you can register a callback function with the XMLHttpRequest and the dispatch the XMLHttpRequest asynchronously; control then return to the browser, but the callback function will be called when the server’s response arrives.

On the java web server, the request arrives just like any other HttpServletRequest. After parsing the request parameter, the Servlet invokes the necessary application logic serializes its response into xml and writes it to the HttpServletResponse.

Back on the client side, the callback function registered on the XMLHttpRequest is now invoked to process the xml document returns by the server.

Finally, the user interface is updated in response to the data from the server, Using JavaScript to manipulate the page’s HTML DOM.


XMLHttpRequest’s method:

Open(): set the stage for call to the server. The method argument can be GET, POST, or PUT. The url argument can be relative or absolute. This method includes three optional arguments.

Void open(String method, String url, Boolean asyn, String username, String password)

Send(): sends the request to the server

Void send(String content)

setRequestHeader(): set the specified header for supplied value. Open() method must be call before attempting to set any header.
Void setRequestHeader(“header”,”value”)
Properties:
Onreadystatechange : The event handler that fires at every state change, typically to a java script function.
readyState: the state of the request. The five possible values are
0 : uninitialized
1 : loading
2 : loaded
3 : Interactive
4 : Complete
responseText : The response form server as a String.
responseXML
status

Example:
Ajax.js
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * by Navindra K. Jha
 */
var xmlhttp=null;
function loadContentfromjsp()
{
    xmlhttp=getXMLHttpRequest();
    if(xmlhttp==null)
        {
            alert("Browser not support Ajax");
        }
        url="Result.jsp";
        xmlhttp.onreadystatechange=callback;
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlhttp.send("name=raj");
}
function loadContentfromservlet()
{
    xmlhttp=getXMLHttpRequest();
    if(xmlhttp==null)
        {
            alert("Browser not support Ajax");
        }
        url="hello"; // Servlet name in dd
        xmlhttp.onreadystatechange=callback;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
}
function callback()
{
   if(xmlhttp.readyState==4)
       {
           document.getElementById("result").innerHTML=xmlhttp.responseText;
       }
}
function getXMLHttpRequest()
{
    var xmlhttp;
    try{
        xmlhttp=new XMLHttpRequest();
    }catch(e)
    {
        try{
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e){
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");  
        }
    }
    return xmlhttp;  
      
}

Index.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="Ajax.js" language="javascript" ></script>
</head>
    <body>
        <h2>Hello World!</h2>
        <a href="javascript:loadContentfromjsp()">Content From Server Using Jsp</a><br/>
        <input type="button" onclick="loadContentfromservlet()" value="servlet"/>

        <div id="result"></div>
    </body>
</html>

result.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h2>Hello <%=request.getParameter("name")%>,Contents From GlashFish Server For Ajax</h2>
    </body>
</html>

Hello.java
package pack;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
          
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet hello</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet hello at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
          
        } finally {
            out.close();
        }
    }

  
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

}

Working Example of Hibernate with explanation


A Hibernate has mainly three components:
1. Hibernate Mapping File (*.hbm.xml)
2. Hibernate Configuration File (*.cfg.xml)
3. Persistence  Object (*.class)

Mapping File: Mapping  the Contact Object to the Database Contact table
The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. 
Here is the code for contact.hbm.xml:

contact table must has ID, firstname, lastname, email field as describe in mapping file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jan 1, 2002 12:34:16 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="hibernateappexample.Contact" table="contact" catalog="stu">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="firstname" type="string">
            <column name="FIRSTNAME" length="25" />
        </property>
        <property name="lastname" type="string">
            <column name="LASTNAME" length="25" />
        </property>
        <property name="email" type="string">
            <column name="EMAIL" length="25" />
        </property>
    </class>
</hibernate-mapping>

Hibernate Configuration file is simple xml documents. In this application Hibernate provided connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. 
Here is the code: 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/stu</property>
    <property name="hibernate.connection.username">root</property>
    <mapping resource="hibernateappexample/Contact.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Persistence Class

Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for Contact.java: 

package hibernateappexample;

public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

  /**
   * @return Email
   */
  public String getEmail() {
    return email;
  }

  /**
   * @return First Name
   */
  public String getFirstName() {
    return firstName;
  }

  /** 
   * @return Last name
   */
  public String getLastName() {
    return lastName;
  }

  /**
   * @param string Sets the Email
   */
  public void setEmail(String string) {
    email = string;
  }

  /**
   * @param string Sets the First Name
   */
  public void setFirstName(String string) {
    firstName = string;
  }

  /**
   * @param string sets the Last Name
   */
  public void setLastName(String string) {
    lastName = string;
  }

  /**
   * @return ID Returns ID
   */
  public long getId() {
    return id;
  }

  /**
   * @param l Sets the ID
   */
  public void setId(long l) {
    id = l;
  }

Setting Up MySQL Database
In the configuration file(contact.cfg.xml) we have specified to use stu database running on localhost.  So, create the databse ("stu") on the MySQL server running on localhost.

Developing Code to Test Hibernate example

Now we are ready to write a program to insert the data into database. We should first understand about the Hibernate's Session. Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file.  Then the save method on session object is used to save the contact information to the database:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hibernateappexample;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author navindra
 */
public class Main {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
    Session session=null;
    Contact contact=null;
    Transaction tx=null;
    SessionFactory factory=null;
    try{
    Configuration cfg=new Configuration().configure("contact.cfg.xml");
    factory=cfg.buildSessionFactory();
    session= factory.openSession();
    tx=session.beginTransaction();
    contact=new Contact();
    contact.setId(3);
    contact.setFirstname("Naveen");
    contact.setLastname("Jha");
    contact.setEmail("jha@gmail.com");
    session.save(contact);
    tx.commit();
    }catch(Exception e){
        System.out.print("Error"+e);
    if(tx!=null){
        try{
            tx.rollback();
        }catch(Exception e1){
        System.out.print("Error"+e1);
        }
    }

    }
  finally{
  if(session!=null){
      try{
          session.flush();
          session.close();
      }
      catch(Exception e2){
      System.out.print("Error"+e2);
      }
  }
  }
    
    }

}

State-Management in java web application with example

State-Management:

HTTP protocol that is used on Internet to send request to receive response is a stateless protocol. I.e. for each request, new http connection is created between client and server and this connection is closed as soon as last byte of response is received by the client.

Q. Why used stateless protocol?
A.  Proper utilization of network

Following four methods:

Cookies:
Cookies are small bits of textual information that a web server sends to a browser and that the browser later returns unchanged when visiting the same web site or domain.
Non persistent: by default are non persistent that is that are lost as soon as communication with the server is stop.
Persistent: persistent cookies are saving in the form of text file by the browser to be reuse when the communication with the server is stop.
Limitation:
Browser dependent method. All the browsers do not’s support cookies for the cookies can be disable from the browser.
Only text information can be persistent with the help of cookies.
Object of javax.servlet.http.Cookie class represent a class.
Public cookie (String name, String vlaue)
Methods:
Public String getName();
Public String getValue();
Public String setmaxAge(time in second);
Public void addCookie();
Public cookie [] getCookies();
Ex:
Cookie ck=new Cookie (“user”,name);
ck.setMaxAge(10000);
response.addCookie(ck);

Hidden Form Field:
It is an invisible text field that is use by the server to maintain state between multiple requests.
<input type=”hidden”> is used to create an invisible text field in a page. Value to be persistent from one request to another is set in the invisible text field. When ever a request is made from the page containing invisible text field value of invisible text fields are send as request parameter.
Limitation:
Hidden Form Field can only be used if there is a form in the page.
Only text information is persisted.
Ex:
Out.println(“<input type=’hiddden’ name=’txtName’ value=”+name”>”);

URL Rewriting
It is used to maintain states between multiple requests in case of hyper links are used to send request.
In case of url rewriting information to be persisted or to be made available in the target resource of the hyperlink is appended as request parameter to the url.
<a href=UrlOfTargetResource?parameterName=dynamicAppendValue&…>Txt</a>
Limitation:
Only in case of hyperlink is used
Ex:
Out.println(“<a href=WelcomeServlet?UserName=”+name+”>Take a Tour</a>”)
In the above three case first of request go to client.

Session
Session object represents a buffer on the server that can be used to maintain state between multiple requests made by client. For each user a session object is provided by the user.
Session is represented by the implementation of javax.servlet.http.HttpSession interface.
Methods:
setAttribute(): used to store an attribute in the session object.
Public void setAttribute(String name, Object value)
Public Object getAttribute(Sting name);
Public Enumeration getAttributeNames();
Public void removeAttribute(String name);
Public Boolean isNew();
Public void setMaxInactiveInterval(long second)
Public void invalidate(); relies the session object
getSession() method of HttpRequestRequest interface is used to create a new session object or to obtain the reference of a existing session object.
HttpSession session=request.getSession(false);
Passing false means the method returns a pre-existing session, or null if there was no session associated with this client.
Passing true same as getSession()
If(session.isNew())
isNew() returns true if the client has not yet responded with this session ID.
If(session==null)
Now we can test for whether there was already a session (the no-arg getSession() would never return null.)

How many way session can die ?

Three ways a session can die:-

a.    If time out
b.    You call invalidate() on the session object
c.    The application goes down(crashes or is underplayed)
Configure a timeout in the DD has virtually the same effect as calling setMaxInactiveInterval() on every session that’s created.
<web-app>
    <servlet>
    </servlet>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
    </web-app>
    session.setMaxInactiveInterval(seconds);

session.invalidate():-
end the session. This includes unbinding all session attributes currently stored in this session.
Some points:
    One problem how does the Container know who the client is?
    The client needs a unique session id-on the client first request, the container generates a unique session ID and gives it back to the client with the response. The client sends back the session ID with each subsequent request.
    How do the client and container exchange Session id info?
    The simplest and most common way to exchange the info is through cookies.
    URL Rewriting will happen automatically if cookies don’t work with client, but you have to explicitly encode all of the URLs you write.
    To encode a URL, call response.encodeURL(a String)
    URL rewriting works with sendRedirect()-there are a special URL encoding method just forthat:
Response.encodeRedirectURL(“/test.do”);

What is Servlet and Why needs Servlet ?

Servlet:
In begining internet consists only static contents written using HTML. Soon dynamic web contents were made possible using CGI technology. CGI enable the web server to call an external program and pass HTTP request information to that external program to process the request. The response from external program to pass back to the web server, which forwards it to the client browser.
When no. of users visiting popular site, CGI had failed to deliver scalable internet application.
Web application development technologies:
ColdFusion, Server Side Java Script (SSJS), PHP, Servlet, Jsp, Asp, Asp.net. Now, Asp (Asp.net) and Servlet/jsp have been the main technology.
A Servlet is a java program that programmatically extends the functionality of a web server in request-response programming model. Servlets are responsible for generating dynamic html. Servlet is executing within a web container and it does not have a visible interface. Servlets are managed objects that are object of a Servlet is created and managed by the web container.
The Servlet aware web server is called Servlet container. It is also known as Servlet engine early.

Default functionality of a web server is that it can only serve static resource. After Servlet, web server can serve static as well as dynamic resources. Servlet technology was introduced in 1996.
Servlet API
Servlet API is provided in javax.servlet and javax.servlet.http package. At the core of Servlet API is an interface name ‘Servlet’.
Javax.servlet.Servlet provides life cycle methods for a Servlet and must be implemented by each Servlet class.
Life cycle methods-
(1)    init()
This method is executed only once when Servlet object is created. This method is used by the web container to provide initialization parameters in the form of ServletConfig object.
Syntax-
public void init (ServletConfig config);
(2)    service()
This method is executed each time request for the Servlet is received. This method is responsible for generating dynamic contain.
Syntax-
public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException;
(3)    destroy()
This method is executed only once when the Servlet object is unloaded form the memory.
Syntax-
public void destroy ();
A part from life cycle method Servlet provide to non-life cycle method that may be used Servlet developer.
(a)    getServletConfig()
return the reference of ServletConfig object.
Syntax: public ServletConfig getServletConfig()
(b)    getServletInfo()
can be used by the Servlet developer to provide information about the Servlet.
Syntax: public String getServletInfo()
Public class YourServlet implements Servlet
{
//Define all method of Servlet interface
}
Javax.servlet.GenericServlet class provides default implementation of Servlet interface.
Public class YourServlet extends GenericServlet
{
//override derived methods
}
GenericServlet class provides protocol independent implementation of Servlet interface. ‘Javax.servlet.http.HttpServlet’ class provides http specific implementation of Servlet interface. This class provides additional methods to handle http request. Most commonly used among these methods are:-
doGet() and doPost(), which are used to handle http get and post request.
Syntax:
public void doGet(HttpServletRequest request, HttpServletResponse respone) throws ServletException, IOException.
public void doPost(HttpServletRequest request, HttpServletResponse respone) throws ServletException, IOException.
In case of get Request request parameter are appended to the url after a question mark and send as a part of request header. Name and value of all request parameter are displayed in the address bar of the browser as well as maximum no. of parameter or size of the data that can be send as request parameter is limited by the size of the header.
In case of post Request request parameter are send as a part of request body (i.e data is sent as a separate link) that means unlimited data can be send as request parameter and name and values of request parameter are not show in the address bar.   
Method attribute of form element (in html page) specifies how the data will be transmitted to the Http Server.
Get is default and is also the method that is used when the user types a URL into the address bar or clicks on a hypertext link.
Advantage of get:
(a)    save the result of a form submission
you can submit data and bookmark the resultant url, send it to a collegeagus by email, or put it in a normal hypertext link.
(b)    Type data in by hand
You can test servlets or jsp pages that use get simply by entering url with appropriate data attached. The ability is convenient during initial development.
Advantage of post:
(a)    Transmit lager amount of data
Many browser limit urls to a few thousand characters, it used when form submit large amount of data.
(b)    Send binary data
Space, tabs, and many other character are illegal in urls. If you upload large binary file. It would be a time consuming process to encode all the characters before transmitting and decoded them on the other end.
(c)         Keep the data private from somone looking over the users shoulder.
Enctype:- This attribute specify the way in which data will be encoded before being transmitted. The default is application/x-www-form-urlencoded.Each space into + sign, = sign between entry name and value, and ampersand (&) between the pairs.
Post data is also encoded as application/x-www-form-urlencoded. Most recent browser support an additional ENCTYPE of multipart/form-data. This encoding transmit each field as a separate part of a MIME compatible document. To use this enctype, you must specify post as the method type. This encoding sometimes make it easier for server side program to handle complex data, and it is required when you are using file upload controls to send entire document.
Why Enctype?
In Http get request, the parameters are appended to the url as a query string, the request url will stick the parameter on the end of the request url. But an http request won’t work correctly if it contains unsafe character.
Each request runs in a separate thread!
You might hear people say things kike, “Each instance of the servlet…”but that’s just wrong. There aren’t multiple instances of any Servlet class, except in one special case (called SingleThreadMode).
The container runs multiple threads to process multiple request to a single Servlet and every client request generates a new pair of request and response objects.
That means multiple thread can concurrently be accessing the same Servlet object. Your doGet() and doPost() method must be careful to synchronize access to field and other share data. Local variables are not shared by multiple threads, and thus need no special protection.
If you implement SingleThreadModel (a marker interface) a single instance of Servlet not used by more than one request.

what is J2EE ?

J2EE-Java 2 Enterprise Edition:

J2EE provide a platform for developing a platform independent, portable, multiuser, secure, and distributed server-side application. EJB is a portion of J2EE.
Java 2 platform for enterprise application.J2EE is a specification their implementation is provided by the vendors in the form of application server or web server.
In J2EE, Sun Microsystem Provided concept of application server.
An Application server is a software package that contains:-
(1)    Web container – To execute web application
(2)    EJB container – To execute EJB modules
(3)    JNDI server – To facilitated registration and searching of resources
(4)    Messaging server – To facilitated asynchronous message passing between different components of an enterprise application.
(5)    UDDI server – To store and look up information about web services
Commonly used Application servers:-
Web logic server
Sun application server
Web sphere
JBoss server
GlashFish
OC4J
Web server is a software package that contains only web container. So Tomcat is not a full j2EE application server. It has not EJB container.
Most common non-EJB web application usually uses Apache and Tomcat together with Apache as the HTTP web server, and Tomcat as the web container. Although the Tomcat container does have the ability to act as a basic HTTP server but Tomcat is not nearly as robust as Apache.


Boxing and Unboxing in java

Boxing and Unboxing:

Suppose we want an array list of integers. Unfortunately, the type parameter inside the angle brackets cannot be a primitive type. It is not possible to form an ArrayList<int>. Here, the Integer wrapper class comes in. It is ok to declare an array list of Integer objects.
ArrayList<Integer> list = new ArrayList<Integer>();
Note: An ArrayList<Integer> is far less efficient than an int[] array because each value is separately wrapped inside an object. You would only want to use this construct for small collections when programmer convenience is more important than efficiency.
The call
list.add(3);
is automatically translated to
list.add(new Integer(3));
This conversion is called autoboxing.
Conversely, when you assign an Integer object to an int value, it is automatically unboxed. That is, the compiler translates
int n = list.get(i);
into
int n = list.get(i).intValue();

Runtime polymorphism and dynamic binding

Runtime polymorphism and dynamic binding:

Resolving a method call that is finding out which method definition is to be executed by a method call is called binding.
Binding is down by the compiler. In normal cases compiler identify a method definition for a method call at compilation time that is method call is resolved at compilation time. Resolving a method call at compilation time is static binding. In case of method overloading static binding is performing.
“Reference variable of a base class can contain the references of its sub class objects.”
Class A{
Public void display()
{
s.out.println(“display of A”);
}
}
Class B extends A{
Public void display(){
s.out.println(“display of B”);
}
}
Class c extends A
{
Public void display(){
s.out.println(“display of C”);
}
}
Class D
{
Public static void main(String as[]){
A x=new A();
B y=new B();
C z=new Z();
callMe(x);
callMe(y);
callMe(z);
}
Private static callMe(A p){
p.display();
}
}
“If a method call to an overridden method is made using the reference variable of the base class then compiler does not bind method call to a method at compilation time, rather it postponed the binding of the method call up to the execution time. When the type of object being referenced by the reference variable becomes known. Such type of method binding is called dynamic or late binding and it facilited run time polymorphism.”
Runtime polymorphism is the facility to invoke different method from a single method calls.
“To create generalize method use run time polymorphism.”
“When a reference variable of a base class is used to refer sub class object then only members are referred which are part of base class.”

Thread and their state



A Thread is a single sequence of execution that can run independently in an application. Knowledge of threads in programs is useful in term of resource utilisation of the system on which an application is running. Multithreaded programming is very useful in network and internet applications developments. Multithreaded programs support more than one concurrent thread of execution. This means they are able to simultaneously execute multiple sequences of instructions. Each instruction sequences have its own unique flow of control that is independent of all others. These independently executed instruction sequences are known as threads.
In single processor system, only a single thread of execution occurs at a given instant, but multiple threads in a program increase the utilization of CPU.


Implementation of Join() method of Thread



Implementation of Join()


public class MyReader {

    BufferedReader b;

    public MyReader() {
        b = new BufferedReader(new InputStreamReader(System.in));
    }
    public String readData(String msg){
        String str;
        try{
            System.out.println(msg);
            str=b.readLine();
            return str;
        }catch(Exception e){System.out.println(e);}
        return null;
    }
}

public class NameThread extends Thread{
final MyReader r;
public NameThread(MyReader reader){
    r=reader;
}
    @Override
public void run(){
        synchronized(r){
            String name=r.readData("Enter name");
    System.out.println("Hello,"+name);
        }
  
}
}
public class MailThread extends Thread{
final MyReader r;
public MailThread(MyReader reader){
    r=reader;
}
    @Override
public void run(){
        synchronized(r){
    String mailId=r.readData("Enter mailId");
    System.out.println("your EmailId "+mailId);
        }
  
}

}
public class ReaderTest {

    public static void main(String as[]) throws Exception{
        MyReader m = new MyReader();
        NameThread nt = new NameThread(m);
        MailThread mt = new MailThread(m);
        nt.start(); // NameThread is started(call made for run method of Name thread  by jvm)
        mt.start(); //MailThread is started(call made for run method of Mail thread  by jvm)
        mt.join();//suspend current thread(main thread) till mailThread not complete
        nt.join();//suspend current thread(main thread) till NameThread not complete

        System.out.println("Execution from main start...!");
    }
}


That means join used to start a thread (mt, nt) and again calling join(mt, nt) to stop current thread(main thread) by providing priority to currently started thread.

Thread Synchronization



Thread Synchronization:

Execution of a thread is asynchronous by nature that is context switch between thread can not be predicted in advance.

 Synchronization is desirable when multiple threads share a common resource in order to use the resource mutually exclusive manner.

E.g. two users did not access the same bank account simultaneously.

“Who thread when execute is not predicated; only no. of thread is fixed.”

Synchronization is achieved in two ways:-

1.    Synchronized method

One or more methods of a class can be declared to be synchronized. When a thread calls an object’s synchronized method, the whole object is locked. This means that if another thread tries to call any synchronized method of the same object, the call will block until the lock is released (which happens when the original call finishes).

synchronized returnType methodName(if arg any){

//statements

}

2.    Synchronized block

There are cases where we need to synchronize a group of statements; we can do that using synchronized statement.

synchronized (object){

object.method();

}

Example:

Synchronized method Test

public class MyReader {

    BufferedReader b;

    public MyReader() {

        b = new BufferedReader(new InputStreamReader(System.in));

    }

    synchronized public String readData(String msg){

        String str;

        try{

            System.out.println(msg);

            str=b.readLine();

            return str;

        }catch(Exception e){System.out.println(e);}

        return null;

    }

}

public class NameThread extends Thread{

final MyReader r;

public NameThread(MyReader reader){

    r=reader;

}

    @Override

public void run(){

     String name=r.readData("Enter name");

    System.out.println("Hello,"+name);

  

}

} public class MailThread extends Thread{

final MyReader r;

public MailThread(MyReader reader){

    r=reader;

}

    @Override

public void run(){

     

    String mailId=r.readData("Enter mailId");

    System.out.println("your EmailId "+mailId);

 

}

}

public class ReaderTest {

    public static void main(String as[]) {

        MyReader m = new MyReader();

        NameThread nt = new NameThread(m);

        MailThread mt = new MailThread(m);

        nt.start();

        mt.start();

    }

}

Synchronized block Test

public class MyReader {

    BufferedReader b;

    public MyReader() {

        b = new BufferedReader(new InputStreamReader(System.in));

    }

    public String readData(String msg){

        String str;

        try{

            System.out.println(msg);

            str=b.readLine();

            return str;

        }catch(Exception e){System.out.println(e);}

        return null;

    }

}

public class NameThread extends Thread{

final MyReader r;

public NameThread(MyReader reader){

    r=reader;

}

    @Override

public void run(){

        synchronized(r){

            String name=r.readData("Enter name");

    System.out.println("Hello,"+name);

        }

  

}

}

public class MailThread extends Thread{

final MyReader r;

public MailThread(MyReader reader){

    r=reader;

}

    @Override

public void run(){

        synchronized(r){

    String mailId=r.readData("Enter mailId");

    System.out.println("your EmailId "+mailId);

        }

 

}

}

public class ReaderTest {

    public static void main(String as[]) {

        MyReader m = new MyReader();

        NameThread nt = new NameThread(m);

        MailThread mt = new MailThread(m);

        nt.start();

        mt.start();

    }

}Output:

Enter name

raj

Hello,raj

Enter mailId

abc

Your EmailId abc

If in above scenarios synchronized method/block is not use then output –

Enter name

Enter mailId

Inter Thread communication



Inter Thread communication

Java provides three methods that threads can use to communicate with each other:

 public final void wait()throws InterruptedException

 public final native void notify(),

 public final native void notifyAll().

These methods are defined for all objects (not just Threads). The idea is that a method called by a thread may need to wait for some condition to be satisfied by another thread. In that case, it can call the wait method, which causes its thread to wait until another thread calls notify or notifyAll.

A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notify (so it is often better to use notifyAll than notify).

wait(long timeout)

public final native void wait(long timeout) throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

“All three methods can be called only from within a synchronized context.”

The rules for using these methods are actually quite simple:

    wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
    notify() wakes up the first thread that called wait() on the same object.
    notifyAll() wakes up all the thread that called wait() on the same object, The highest priority thread will run first.

public class Student {

String name=null;

synchronized String getName(){

    System.out.println("getName() called..");

    if(name==null)

    {

        try{

            wait();

        }catch(Exception e){}

    }

    System.out.println("Name "+name);

  //  name=null;

    return name;

}

synchronized void putName(String name){

    System.out.println("putName() called...");

    this.name=name;

    notify();//notifyAll() can be called

}

}

public class GetThread extends Thread {

    Student s;

    GetThread(Student s) {

        this.s = s;

    }

    @Override

    public void run() {

        String sname = s.getName();

        if (sname.equals("Raj")) {

            System.out.println("User:" + sname);

        } else {

            System.out.println("Guesst:" + sname);

        }

    }

}

public class PutThread extends Thread {

    Student s;

    PutThread(Student s) {

        this.s = s;

    }

    @Override

    public void run() {

        s.putName("Raj");

    }

}

public class StudentTest {

public static void main(String as[]){

    Student s=new Student();

    GetThread gt=new GetThread(s);

    PutThread pt=new PutThread(s);

    gt.start();

    pt.start();

   }

}

In above example GetThread is first of all started  and called student object’s getName() method, but name is null so suspended till PutThread which is also in queue for execution not set the name by calling setName() method, after PutThread set name call notify to wake up GetThread again and print name; It is also clear form above one thread call wait() on student object and other call notify on student object.

Other producer and consumer example:-

public class Q {

    int n;

    boolean valueSet = false;

    synchronized int get() {

        if (!valueSet) {

            try {

                wait();

            } catch (Exception e) {

                System.out.println(e);

            }

        }

        System.out.println("Got: " + n);

        valueSet = false;

        notify();

        return n;

    }

    synchronized void put(int n){

        if(valueSet){

            try{

                wait();

            }catch(Exception e){System.out.println(e);}

        }

        this.n=n;

        valueSet=true;

        System.out.println("Put: "+n);

        notify();

    }

}

public class Consumer implements Runnable {

    Q q;

    Consumer(Q q) {

        this.q = q;

        new Thread(this, "Consumer").start();

    }

    public void run() {

        while (true) {

            q.get();

        }

    }

}

public class Producer implements Runnable {

    Q q;

    Producer(Q q) {

        this.q = q;

        new Thread(this, "Producer").start();

    }

    public void run() {

        int i = 0;

        while (true) {

            q.put(i++);

        }

    }

}

public class PCFixed {

public static void main(String as[]){

    Q q=new Q();

    new Consumer(q);

    new Producer(q);



    System.out.println("Press Control-c to stop.");

}

}

Difference between Multithreading and Multiprocessing



Multiprocessing:

ü  To obtain maximum throughput

ü  To reduce average execution time of process


A Thread is a single sequence of execution that can run independently in an application.
Multithreaded programs support more than one concurrent thread of execution

Multithreading represents concurrent execution of multiple threads. Multithreading is a lightweight version of multiprocessing i.e. less over head is incurred by the o.s. in multithreading as compare to multiprocessing.

Difference between Multithreading and Multiprocessing

ü  In multiprocessing each process represents an independent application where as in multithreading each thread represents an independent module of an application.

ü  Each process as it own addresses space where as all the threads in an application share a common address space.

Difference between Thread and Process:

ü  Thread share address space of the process that created it; processes have their own address space.

ü  Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.

ü  Change to the main thread (cancellation, priority change) may affect the behavior of the other threads of the process; change to the parent process does not affect child process.

A Thread is represents by an instance of java.lang.Thread class. This class provides various methods to obtain the state of a thread, to change the state of thread, to request the execution of the thread, to suspend the execution of the thread etc. All methods in thread class except one are final.

“A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon.”

“When java program startup, one thread begins running immediately. This is usually called the main Thread of your program, because it is the one that is executed when your program begins.”

Main thread is important for two reasons:

    It is thread from which other “child” threads will be spawned.
    Often it must be the last thread to finish execution because it performs various shutdown actions.

Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread(), which is public static member of Thread.

public class MainThreadTest {

public static void main(String as[])throws Exception{

    Thread th=Thread.currentThread();

    System.out.println(th.getName());

    System.out.println(th.getPriority());

    Thread.sleep(1000);

    th.setName("Main Thread");

    th.setPriority(7);

    System.out.println(th.getName());

    System.out.println(th.getPriority());

}

}

Out put:

main

5

Main Thread

7