JQuery Deferreds and Promises

The Deferred Object :

http://jsfiddle.net/shivanshu/7gnnA/

The “Deferred” pattern describes an object which acts as a proxy for some unit of computation that may or may not have completed.
In their simplest form, deferreds allow you to specify what will occur when a computation completes or fails. jQuery’s specific implementation allows you to register callback functions that will run if a deferred resolves successfully, if it is rejected with errors, or if it is notified of some “progress” towards a resolved state

A deferred object starts in a pending state, this means it is not yet completed. While in the pending state if the resolve() function is called then the state is changed to resolved, and if the reject() function is called then the state is changed to rejected.

Promise : Creating A Safety Net Around Our Deferred Object :

We can protect our Deferred objects from state changes by other code by creating a Promise object for the Deferred using the deferred.promise() method.

The promise exists purely for encapsulation: If you return a Deferred from a function, it might be resolved or rejected by the caller. But if you only return the pure Promise corresponding to that Deferred, the caller can only read its state and attach callbacks.

promise-validation-promise

Working with jQuery Deferred :

Creating Deffered Object :

// create a new deferred

// With the new special operator
var deferredObj = new $.Deferred();

//the new operator is optional.
var deferredObj = $.Deferred();

Binding Callbacks To Our Deferred Objects :

We can bind callbacks to our Deferred objects through the deferred.then(), deferred.done(), deferred.fail(), deferred.always(), deferred.pipe() and deferred.progress() methods.

var ourDeferred = $.Deferred();
// Our callbacks

//success
deferredObj.done( doneCallbacks );

//failure
deferredObj.fail( failCallbacks );

//progress
deferredObj.progress( progressCallbacks );

//Or We can also achieve the same using the deferred.then() shorthand method
deferredObj.then( doneCallbacks, failCallbacks, progressCallbacks );

Changing the state of Our Deferred Objects :

  • Success :
  • deferredObj.resolve();
    
  • Failure :
  •  dfd.reject();
    

    Complete code :

    // create a new deferred
    var dfd = $.Deferred();
    
     dfd.done( function() {
      alert( 'done!');
     });
    
     dfd.resolve();
    

    Passing parameters to resolve and reject :
    The arguments given to the resolve() or the fail() functions are passed to the callbacks so the object that resolved or failed the deferred object can be used.

    // create a new deferred
    var dfd = $.Deferred();
    
     dfd.done( function( data ) {
      alert( 'done!' + data );
     });
    
     dfd.resolve( 'yay!' );
    

    All these functions return the deferred object so they can be chained together to make the code more concise, like this:

    $.Deferred().done(function( data ) {
      alert( 'done!' + data );
     }).resolve('hello');
    

    Working with jQuery Promise :

    Creating Promise Object :

    // create a new deferred
    var dfd = $.Deferred();
    
    //get promise from deffred
    var prom = dfd.promise();
    

    Binding Callbacks To Our Promise Objects :

    We can bind callbacks to our Deferred objects through the deferred.then(), deferred.done(), deferred.fail(), deferred.always(), deferred.pipe() and deferred.progress() methods.

    var ourDeferred = $.Deferred();
    var ourPromise = ourDeferred.promise();
    // Our callbacks
    
    //success
    ourPromise.done( doneCallbacks );
    
    //failure
    ourPromise.fail( failCallbacks );
    
    //progress
    ourPromise.progress( progressCallbacks );
    
    //Or We can also achieve the same using the deferred.then() shorthand method
    ourPromise.then( doneCallbacks, failCallbacks, progressCallbacks );
    

    We can’t change the state through Promise

    Complete code :

    var dfd = $.Deferred();
    var prom = dfd.promise();
     prom.done( function( data ) {
      alert( 'done!' + data );
     });
     dfd.resolve( 'yay!' );
    

    Deffered Vs Promise

    DefAndPr

    promises

    creating defferd from your function :

    function someFunction() {
     var deferred = $.Deferred();
     // async wait 2 seconds:
     setTimeout(function () {
         alert('Inside function');
       deferred.resolve();
     }, 2000);
     return deferred.promise();
    };
    
    someFunction()
     .done(function () {
     alert('return from function');
     });
    

    Note :

    Resolving multiple jQuery deferreds using $.when

    $.when provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

    function someFunction1(message) {
     var deferred = $.Deferred();
     // async wait 2 seconds:
     setTimeout(function () {
         alert('In first function: ' + message);
       deferred.resolve(message);
     }, 2000);
     return deferred.promise();
    };
    
    function someFunction2(message) {
     var deferred = $.Deferred();
     // async wait 2 seconds:
     setTimeout(function () {
         alert('In second function: ' + message);
       deferred.resolve(message);
     }, 2000);
     return deferred.promise();
    };
    
    $.when(someFunction1('foo'), someFunction2('bar'))
     .done(function (argFoo, argBar) {
     alert('return from first function: ' + argFoo);
     alert('return from second function: ' + argBar);
     });
    

    In the case where multiple Deferred objects are passed to jQuery.when, the method returns the Promise from a new “master” Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, it is passed the resolved values of all the Deferreds that were passed to jQuery.when. For example, when the Deferreds are jQuery.ajax() requests, the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list.

    In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.

    If any of the deferreds are rejected, then the entire $.when will fail. In this case, the .fail callback function is called.

    function someFunction1(message) {
     var deferred = $.Deferred();
     // async wait 2 seconds:
     setTimeout(function () {
         alert('In first function: ' + message);
       deferred.reject(message);
     }, 2000);
     return deferred.promise();
    };
    
    function someFunction2(message) {
     var deferred = $.Deferred();
     // async wait 2 seconds:
     setTimeout(function () {
         alert('In second function: ' + message);
       deferred.reject(message);
     }, 2000);
     return deferred.promise();
    };
    
    
    $.when(someFunction1('foo'), someFunction2('bar'))
     .done(function (argFoo, argBar) {
     alert('return from first function: ' + argFoo);
     alert('return from second function: ' + argBar);
     })
    .fail( function (error) {
        alert('Failed due to: '+error);  
    });
    

    Note :

    If a single argument is passed to jQuery.when and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original argument. In this case any failCallbacks you might set are never called since the Deferred is never rejected. For example:

    $.when( { testing: 123 } ).done(function( x ) {
      alert( x.testing ); // Alerts "123"
    });
    

    For more info https://api.jquery.com/jQuery.when/

    Advertisements

    RESTful Web Service using Jersey and no web.xml

    Open Eclipse, File→New→Dynamic Web Project.

    Jersey
    Download Jersey from the Jersey website.

    http://jersey.java.net/ 
    

    Copy all JARs from your Jersey download into the WEB-INF/lib folder.

    Resource class

    Description: @Path annotation at class level says that all the resources in this class is accessed by prefixing the path “/hello”.

    The method getPlain() serves a resource by the name “/plain” in data format “text/plain” via HTTP GET request.

    package sample.rs;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    @Path("hello")
    public class HelloWorldResources {
    	@GET
    	@Produces({ MediaType.TEXT_PLAIN })
    	@Path("/plain")
    	public String getPlain() {
    		return "Hello World!!!";
    	}
    }
    

    Deployment options :

    JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and provider classes, and root resource and provider singleton instances. A Web service may extend this class to declare root resource and provider classes. For example,

  • Deployment agnostic application model
  • public class MyApplication extends Application {
        @Override
        public Set<Class<?>> getClasses() {
            Set<Class<?>> s = new HashSet<Class<?>>();
            s.add(HelloWorldResource.class);
            return s;
        }
    }
    

    Alternatively it is possible to reuse one of Jersey’s implementations that scans for root resource and provider classes given a classpath or a set of package names. Such classes are automatically added to the set of classes that are returned bygetClasses. For example, the following scans for root resource and provider classes in packages “org.foo.rest”, “org.bar.rest” and in any sub-packages of those two:

  • Reusing Jersey implementation in your custom application model
  • public class MyApplication extends ResourceConfig {
        public MyApplication() {
            packages("org.foo.rest;org.bar.rest");
        }
    }
    

    In Servlet 2.x compatible container with web.xml
    When running in a Servlet 2.x then instead it is necessary to declare the Jersey specific servlet and pass the Application implementation class name as one of the servlet’s init-param entries:

  • Deployment of your application using Jersey specific servlet
  • <web-app>
        <servlet>
            <servlet-name>Jersey Web Application</servlet-name>
            <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>javax.ws.rs.Application</param-name>
                <param-value>org.foo.rest.MyApplication</param-value>
            </init-param>
            ...
        </servlet>
        ...
    </web-app>
    

    If there is no configuration to be set and deployed application consists only from resources and providers stored in particular packages, Jersey can scan them and register automatically:

  • Using Jersey specific servlet without an application model instance
  • <web-app>
        <servlet>
            <servlet-name>Jersey Web Application</servlet-name>
            <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>jersey.config.server.provider.packages</param-name>
                <param-value>org.foo.rest;org.bar.rest</param-value>
            </init-param>
            ...
        </servlet>
        ...
    </web-app>
    

    In Servlet 3.0 compatible container(like tomcat 7) without web.xml

    There are multiple deployment options for the class that implements Application interface in the Servlet 3.0 container. For simple deployments, no web.xml is needed at all. Instead, an @ApplicationPath annotation can be used to annotate the user defined application class and specify the the base resource URI of all application resources:

  • Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0
  • @ApplicationPath("resources")
    public class MyApplication extends ResourceConfig {
        public MyApplication() {
            packages("org.foo.rest;org.bar.rest");
        }
        ...
    }
    

    In Servlet 3.0 compatible container(like tomcat 7) with web.xml
    Another deployment option is to declare JAX-RS application details in theweb.xml. This is usually suitable in case of more complex deployments, e.g. when security model needs to be properly defined or when additional initialization parameters have to be passed to Jersey runtime. JAX-RS 1.1 specifies that a fully qualified name of the class that implements Application may be declared in the element of the JAX-RS application’s web.xml. This is supported in a Web container implementing Servlet 3.0 as follows:

  • Deployment of a JAX-RS application using web.xml with Servlet 3.0
  • <web-app>
        <servlet>
            <servlet-name>org.foo.rest.MyApplication</servlet-name>
        </servlet>
        ...
        <servlet-mapping>
            <servlet-name>org.foo.rest.MyApplication</servlet-name>
            <url-pattern>/resources</url-pattern>
        </servlet-mapping>
        ...
    </web-app>
    

    Note that the element is omitted from the servlet declaration. This is a correct declaration utilizing the Servlet 3.0 extension mechanism. Also note that is used to define the base resource URI.

    Example :

  • In Servlet 3.0 compatible container(like tomcat 7) with web.xml
  • package sample.rs;
    
    import java.util.HashSet;
    import java.util.Set;
    
    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;
    
    @ApplicationPath("/testapp")
    public class HelloWorldApplication extends Application {
    	@Override
    	public Set<Class<?>> getClasses() {
    		Set<Class<?>> set = new HashSet<>();
    		set.add(HelloWorldResources.class);
    		return set;
    	}
    }
    

    In Eclipse Run as — >> Run on server

    Test the service using http://localhost:8080/MyRSWebService/testapp/hello/plain

    For more info :

    http://dev.cs.uni-magdeburg.de/java/javaee-6.0/whatSnew/Session5Jersey-JavaEE6_Webinar.pdf

    https://jersey.java.net/nonav/documentation/2.0/deployment.html

    A Simple Document Style Web Service and Client using JAX-WS

    Open Eclipse create a new Dynamic Web project.

    Creating and deploying Web Service

    Create your Web Service interface :
    In src folder of your project create Web Service interface.

    package sample.ws;
    
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    @WebService
    public interface Greeting {
    	@WebMethod
    	String sayHello();
    }
    

    The @WebService annotation defines the Greeting class as a Web Service Endpoint Interface(SEI).

    Create your Web Service implementation :

    Specify the interface HelloWorld by adding the Endpoint Interface element to the @WebService annotation in the implementation class GreetingImpl. You must provide the full package name of the interface.

    Read more: http://mrbool.com/an-introduction-to-java-web-services-programming/28116#ixzz2zCrv0Gzh

    package sample.ws;
    
    import javax.jws.WebService;
    
    @WebService(endpointInterface = "sample.ws.Greeting")
    public class GreetingImpl implements Greeting {
    
    	@Override
    	public String sayHello() {
    		return "Hello, Welcom to jax-ws";
    	}
    
    }
    

    The web service is ready for deployment.

    • You can deploy this in two ways
    • Standalone deployment :

    JAX-WS based web services normally run on a JEE web container or application server. That’s great for production purposes, as those servers provide a very high level of scalability, security infrastructure, monitoring facilities etc.

    But during development repeated deployments to a JEE container can be rather time consuming. JAX-WS’ Endpoint class provides an interesting alternative here, as it allows to host JAX-WS web services within plain Java SE applications.

    A web service hosted that way can very easily be launched and debugged from within your IDE for instance, which is great for development and testing purposes.

    If you go with the code-first approach for web service development, things are really straight-forward.

    In this approach, you just need to have a main method and call the Endpoint.publish(url, provider) . This is mentioned below. This creates web service run-time environment that shipped with Java SE 6 and deploys it into light-weight http server. The service is accessible with the url provided as input to the publish method.

    package sample.ws.client;
    
    import javax.xml.ws.Endpoint;
    
    import sample.ws.GreetingImpl;
    
    public class PublishGreetingServiceWithEndPoint {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		Endpoint.publish("http://localhost:8080/MyWebServices/greeting", new GreetingImpl());
    	}
    
    }
    

    For more info http://musingsofaprogrammingaddict.blogspot.in/2009/04/using-jax-ws-endpoint-api.html

    • Deployment on to a servlet-container :

    In this approach, we can deploy the web service by creating a standard java web application .war file and deploying that to a web server which has got a servlet container support, such as Tomcat.

    You need generate Web Services classes, open your command line, and type :

    cd E:\workspace\MyWebServices
    
    wsgen -s src -d build/classes -cp build/classes sample.ws.GreetingImpl
    

    now you have two classe(SayHello.java, SayHelloResponse.java) generated under src/sample/ws/jaxws.

    Now we need to write our web.xml and put it under /WebContent/WEB-INF :

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                             http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">
       <listener>
         <listener-class>
            com.sun.xml.ws.transport.http.servlet.WSServletContextListener
         </listener-class>
       </listener>
       <servlet>
          <servlet-name>GreetingWS</servlet-name>
          <servlet-class>
            com.sun.xml.ws.transport.http.servlet.WSServlet
          </servlet-class>
    
       </servlet>
       <servlet-mapping>
         <servlet-name>GreetingWS</servlet-name>
         <url-pattern>/greeting</url-pattern>
       </servlet-mapping>
    </web-app>      
    
    • WSServletContenxtListener :

    The listener class(com.sun.xml.ws.transport.http.servlet.WSServletContextListener) mentioned above is the web service context listener, which initializes the web service context when the application context is initialized and creates a web service delegate which is used to delegate all future web service requests and route them to appropriate end point implementation defined in the sun-jaxws.xml mentioned below. This stores the created delegate in the container servlet context, so that the delegate can be accessed by other servlets.

    • WSServlet :

    The servlet definition and it’s mapping is used to intercept the url-pattern that should be considered as web service request.

    The class(com.sun.xml.ws.transport.http.servlet.WSServlet) acts as a dispatching servlet that routes the request to appropriate implementation class through the delegate received from the servlet context created by the listener as stated above.

    Add sun-jaxws.xml under WebContent :
    This file is needed by the JAX-WS reference implementation to map the service implementation class with the service interface. The content of this file is mentioned below.

    <?xml version="1.0" encoding="UTF-8"?>
    <endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
      <endpoint
         name="GreetingWS"
         implementation="sample.ws.GreetingImpl"
         url-pattern="/greeting"/>
    </endpoints>
    
    • sun-jaxws.xml descriptor:

    Each endpoint definition, in this descriptor indicates the name of the web service, implementation class and the url-pattern that routes to this web service invocation. This is read by the context listener and handed-over to the web service delegate created by it, so that the delegate knows which implementation class to invoke when a web service request came-in.

    sun-jaxws.xml is a proprietary deployment descriptor needed when web services are deployed as a standard WAR archive on a non-Java EE5 servlet container using the SUN’s reference implementation.

    Sun’s RI uses WSServletContextListener as the listener for servlet context events and WSServlet as the dispatcher servlet; both of which have to be declared in web.xml. The sun-jaxws.xml file is then required to define web service end points for the WSServlet to let it know to which end point a service request must be dispatched.

    In this way, web services can be run in any JAX-WS RI enabled servlet container, although they won’t be portable.

    Java EE 5+ compliant application servers such as Glassfish, the reference implementation, comply to JSR 109 (Web services 1.2/1.3) and JSR 224 (JAX-WS 2.0/2.1/2.2) and do not require non-standard sun-jaxws.xml deployment descriptors.

    For more info http://stackoverflow.com/questions/12581751/sun-jaxws-xml-when-is-it-needed-and-when-not

    Now you need to download JAX-WS library and put jars under WebContent/WEB-INF/lib :

    Download from : https://jax-ws.java.net/

    Great, now you just need to export this project as a war, and drop it under your Tomcat webapps folder.

    Run Tomcat

    Test the deployment by invoking http://localhost:8080/MyWebServices/greeting?wsdl
    You will get wsdl file on browser.

    Creating Consumer(Client) to access exposed methods

    • There are two ways to create client :
    • By writing cleint code

    Specify the URL :

    url = new URL("http://localhost:8080/MyWebServices/greeting?wsdl");
    

    Specify the qualified namespace :

    QName qname = new QName("http://ws.sample/", "GreetingImplService");
    

    It consists of two parameters (namespaceURI and localPart) :

    • namespaceURI is the @namespace value in the WSDL file
    • The localPart is the value of the service[@name] attribute at the bottom of WSDL

     

    Using the url and qualified name create the service.

    Service service = Service.create(url, qname);
    

    Get the port(proxy to the service), and interact with the webservice.

    Greeting hello = service.getPort(Greeting.class);
    hello.sayHello();
    

    Complete file looks like below :

    package sample.ws.client;
    
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import javax.xml.namespace.QName;
    import javax.xml.ws.Service;
    
    public class GreetingServiceClient {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		URL url;
    		try {
    			url = new URL("http://localhost:8080/MyWebServices/greeting?wsdl");
    			QName qname = new QName("http://ws.sample/", "GreetingImplService");
    
    			Service service = Service.create(url, qname);
    
    			Greeting hello = service.getPort(Greeting.class);
    
    			System.out.println(hello.sayHello());
    		} catch (MalformedURLException e) {
    			e.printStackTrace();
    		}
    
    	}
    
    }
    

    Java Web Service Client via wsimport tool

    We can use “wsimport” tool to parse the published wsdl file, and generate necessary client files (stub) to access the published web service.

    Open the command prompt and issue the following command to generate the files :

    wsimport -s src -d bin -p sample.ws.client http://localhost:8080/MyWebServices/greeting?wsdl
    

    This will generate, one interface and one service implementation file as follows :

    package sample.ws.client;
    
    import javax.jws.WebMethod;
    import javax.jws.WebResult;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.XmlSeeAlso;
    import javax.xml.ws.RequestWrapper;
    import javax.xml.ws.ResponseWrapper;
    
    
    /**
     * This class was generated by the JAX-WS RI.
     * JAX-WS RI 2.2.4-b01
     * Generated source version: 2.2
     * 
     */
    @WebService(name = "Greeting", targetNamespace = "http://ws.sample/")
    @XmlSeeAlso({
        ObjectFactory.class
    })
    public interface Greeting {
    
    
        /**
         * 
         * @return
         *     returns java.lang.String
         */
        @WebMethod
        @WebResult(targetNamespace = "")
        @RequestWrapper(localName = "sayHello", targetNamespace = "http://ws.sample/", className = "sample.ws.client.SayHello")
        @ResponseWrapper(localName = "sayHelloResponse", targetNamespace = "http://ws.sample/", className = "sample.ws.client.SayHelloResponse")
        public String sayHello();
    
    }
    
    
    package sample.ws.client;
    
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.namespace.QName;
    import javax.xml.ws.Service;
    import javax.xml.ws.WebEndpoint;
    import javax.xml.ws.WebServiceClient;
    import javax.xml.ws.WebServiceException;
    import javax.xml.ws.WebServiceFeature;
    
    
    /**
     * This class was generated by the JAX-WS RI.
     * JAX-WS RI 2.2.4-b01
     * Generated source version: 2.2
     * 
     */
    @WebServiceClient(name = "GreetingImplService", targetNamespace = "http://ws.sample/", wsdlLocation = "http://localhost:8080/MyWebServices/greeting?wsdl")
    public class GreetingImplService
        extends Service
    {
    
        private final static URL GREETINGIMPLSERVICE_WSDL_LOCATION;
        private final static WebServiceException GREETINGIMPLSERVICE_EXCEPTION;
        private final static QName GREETINGIMPLSERVICE_QNAME = new QName("http://ws.sample/", "GreetingImplService");
    
        static {
            URL url = null;
            WebServiceException e = null;
            try {
                url = new URL("http://localhost:8080/MyWebServices/greeting?wsdl");
            } catch (MalformedURLException ex) {
                e = new WebServiceException(ex);
            }
            GREETINGIMPLSERVICE_WSDL_LOCATION = url;
            GREETINGIMPLSERVICE_EXCEPTION = e;
        }
    
        public GreetingImplService() {
            super(__getWsdlLocation(), GREETINGIMPLSERVICE_QNAME);
        }
    
        public GreetingImplService(WebServiceFeature... features) {
            super(__getWsdlLocation(), GREETINGIMPLSERVICE_QNAME, features);
        }
    
        public GreetingImplService(URL wsdlLocation) {
            super(wsdlLocation, GREETINGIMPLSERVICE_QNAME);
        }
    
        public GreetingImplService(URL wsdlLocation, WebServiceFeature... features) {
            super(wsdlLocation, GREETINGIMPLSERVICE_QNAME, features);
        }
    
        public GreetingImplService(URL wsdlLocation, QName serviceName) {
            super(wsdlLocation, serviceName);
        }
    
        public GreetingImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
            super(wsdlLocation, serviceName, features);
        }
    
        /**
         * 
         * @return
         *     returns Greeting
         */
        @WebEndpoint(name = "GreetingImplPort")
        public Greeting getGreetingImplPort() {
            return super.getPort(new QName("http://ws.sample/", "GreetingImplPort"), Greeting.class);
        }
    
        /**
         * 
         * @param features
         *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
         * @return
         *     returns Greeting
         */
        @WebEndpoint(name = "GreetingImplPort")
        public Greeting getGreetingImplPort(WebServiceFeature... features) {
            return super.getPort(new QName("http://ws.sample/", "GreetingImplPort"), Greeting.class, features);
        }
    
        private static URL __getWsdlLocation() {
            if (GREETINGIMPLSERVICE_EXCEPTION!= null) {
                throw GREETINGIMPLSERVICE_EXCEPTION;
            }
            return GREETINGIMPLSERVICE_WSDL_LOCATION;
        }
    
    }
    

    Create a Java web service client which depends on the above generated files :

    package sample.ws.client;
    
    public class GreetingServiceClientFromWsImport {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		GreetingImplService greetingImplService = new GreetingImplService();
    		Greeting greeting = greetingImplService.getGreetingImplPort();
    		System.out.println(greeting.sayHello());
    	}
    
    }
    

    For more info http://mrbool.com/an-introduction-to-java-web-services-programming/28116

    Hybrid Applications And Android Native Browser

    Hybrid Applications(web apps within a Webview container):

    Native_html5_hybrid

    These apps are installed on a device, like their pure native app counterparts, while the user interface (UI) is based on HTML5.  This UI runs locally within the native container(Webview), which usually leverages the device’s browser engine.  The advantage of using HTML5 is a consistent, cross-platform UI that works well on most devices.  Combining this with the native container, which is installed on-device, provides mobile users with access to local device services, such as camera, GPS, and local device storage.

    We are using HTML5 today to build rich, interactive web pages (or web apps) then you’re already familiar with the benefits of using HTML5 as a tool to deploy across multiple browser and OS platforms. Cross-platform apps built on HTML5 are a logical extension to this model, where the platform is not a browser (such as Chrome*, Safari* or Firefox*) but the internal web runtime (aka webview) on the target platform.

    HTML5 apps are not limited to web pages viewed in a browser. You can also package your HTML5 code and deploy it as a locally installed hybrid web app. This enables use of the same distribution and monetization channels as native apps, as well as the same installation and launch experience. Rather than running within a sandboxed browser window frame, your app runs in a full-screen webview, with full control over screen real estate and device capabilities.

    Hybrid Architecture Concepts & Fundamentals :

    Mobile-App-Tech-Stacks

    1

    Hybrid Applications consist of native code that creates an embedded web browser used to
    render parts of the application user interface which are written in standard HTML, JavaScript
    and CSS formats.
    The actual browser engine used within the embedded web browser and it’s configuration
    options are provided by the device operating system vendor. The browser engine’s
    implementation changes between versions of the operating system, usually the same browser
    engine technology is kept and just a newer version of the browser engine is used when an
    O/S is updated, but sometimes completely different browser engines are used in newer
    versions of the O/S. Across different operating systems, completely different browser engine
    implementations are used (eg. WinPhone8 – Internet Explorer/Trident, Apple iOS – Safari/
    Webkit), even though they may be based off of the same underlying browser engine codebase.
    Even if an operating system provides a specific browser engine, parts of the browser engine can
    be replaced by carriers (that have forked the primary O/S for their devices or markets). A good
    example of this is Webkit, which has replaceable subsystems that are implemented differently
    on different operating systems (eg. iOS, Android, Blackberry).
    It’s also important to realize that the embedded web browser engine used inside the webview
    native code of the hybrid app often has different capabilities enabled from the default
    standalone browser application provided by the mobile operating system vendor. There is
    no guarantee that the browser engine used by the default browser will have exactly the same
    features and runtime characteristics as the browser used by the embedded webview API
    provided by the same O/S vendor and version. As an example, see the next section about
    Android’s browser engines changing in different versions of Android O/S.

    The Android browser
    Which one do you mean?
    Traditionally Android provides a rendering engine based on WebKit called the WebView. The Android browser — simply called Internet — uses the WebView. But other browsers and any application that need to render HTML can use it too, including apps that have been build using web technologies with PhoneGap.
    Unfortunately the standard WebView is pretty bad. It has quite a few rendering issues and missing support for established web standards. And because the Android browser uses the WebView it too has been pretty bad. The last major update it got was with Android 4.0.
    That is why vendors have actually started making ‘improvements’ to the WebView they ship on their phones or tablets. They took the open-source WebView and made quite a few improvements. But also introduced quite a few new bugs and other issues. Sometimes they just enabled features that were deliberately disabled in the standard WebView, because the current implementation was not yet ready for public use. Sometimes they started using updated version of WebKit. And sometimes they implemented new features on their own, but almost nobody shared the work they did on the WebView and contributed it back to Android itself.
    So we ended up with devices that use the standard unmodified WebView and devices that use their own modified version. As a result you can take 5 different phones using the same Android version and end up with 5 different HTML5test.com scores. This is a complete nightmare if you want to test your site or webapp on Android. If your site works with a particular version of Android on one phone, there is no guarantee it will work on another with the same version. Let alone on a different version!
    The Android browser is still relevant
    The common wisdom is that with recent versions of Android, the Android browser has been replaced with Chrome. While this is true on Nexus devices, this is certainly not the case for other devices.
    The open source version of Android does not include the Chrome browser and still uses the old Android browser. And almost all non-Nexus devices are based on the open source version. I haven’t found a single non-Nexus device that does not have the Android browser in one form or another. And even if Chrome is pre-installed, the Android browser is often still the default browser.
    And even if you have a Nexus device without the Android browser, the default WebView is still there. Any application that wants to render HTML still uses the default WebView and does not care if Chrome is installed or not.
    Even more variations
    So we have the Android browser which either uses the default WebView or one of a dozen modified versions of the WebView. But we also have another variation we haven’t covered yet.
    Every Samsung device released after the Galaxy S III uses an improved version of the default WebView. This includes the S4 and later, but on these more recent devices the Android browser does not use the WebView anymore. What Samsung did was modify the Android browser so it can use the rendering engine from Chromium.
    The first version of this new Android browser was used on the S4 and all of its variants.This first attempt is based on Chromium 18 and as of the Note 3, it has been updated to use Chromium 28.
    On the Galaxy S III, the Tab 2, Tab 3, Note 8.0, Note 10.1 and many others we have the following rendering engines:
    • the modified WebView — used by the Android browser
    • Google Chrome (not installed by default on all)
    On the Galaxy S4, S4 Mini, S4 Zoom and S4 Active we have:
    • the modified WebView
    • the Android browser which uses Chromium 18
    • Google Chrome itself
    So on the Note 3 and Note 10.1 (2014) we have the following rendering engines:
    • the modified WebView
    • the Android browser which uses Chromium 28
    • Google Chrome itself
    Just one more complication: it seems like Samsung is even shipping different variants of their Chromium 28 based Android browser. The Note 3 does not support the WebAudio API, while it is available on the Note 10.1 (2014).

    Which HTML rendering engine does the JellyBean WebView use ?

    (http://bricolsoftconsulting.com/jellybean-webview-html-rendering-engine/)

    We often work with hybrid Android apps that have both native code (written in Java) and web code (written in HTML /JavaScript). When we do, we often need a quick way to test whether the HTML component works properly. Typically, this means loading the HTML in a mobile browser. If the HTML loads successfully and renders correctly, then the HTML should also work in the app’s webview.
    When we do this kind of testing, we try to make sure that the web browser employed for testing uses the same HTML redering engine as the webview. On Android versions up to JellyBean, this means using the classic Android browser, which according to Google shares the same rendering engine as the webview. On JellyBean though, with Google’s introduction of the Chrome browser and with some talk about a Chrome-based webview, things got a bit murky… Does the JellyBean webview use the Android Browser or the Google Chrome rendering engine? Which browser should you use to test your HTML on JellyBean?
    To get a definitive answer to this question we are going to dive into the Android codebase. For that, we will turn toGrepCode, a site that lets anyone quickly browse multiple versions of the Android OS codebase without needing to download the multi-gigabyte source code repositories.
    We begin our search in the source code for Android 4.2.2 r1, which can be found here.
    Since we’re interested in the WebView class, let’s find that class in the source code. We know from the Android documentation that the WebView class is located in the android.webkit package. You can browse to that package and open the WebView.java file.

    What we find :

    private static final String DEFAULT_WEBVIEW_FACTORY = “android.webkit.WebViewClassic$Factory”;
    private static final String CHROMIUM_WEBVIEW_FACTORY = “com.android.webviewchromium.WebViewChromiumFactoryProvider”;

    As you can see from these last two code snippets, the default WebView provider is still the “classic” webview that is based on the Android Browser rendering engine. Apparently there is work underway to switch the webview to the Chrome rendering engine, but right now that’s only available in debug Android builds using a special flag.
    Based on an examination of the Android source code, the webview does not use the Chrome rendering engine in Android 4.2 (JellyBean). The webview is still powered by the Android Browser rendering engine.

    Android WebView History
    Currently, there are the following versions of Android in the marketplace:

    Untitled

    Here Comes Chromium
    As you can see from the table above, in Android 4.0, the platform’s default browser application
    changed from an Android webkit fork to use the new Chromium engine based on Blink.
    Chromium (the same browser engine that Google Chrome’s desktop browsers are based on)
    supports more HTML5 features and has better support of many of the same features that were in the Android Default browser engine.

    Android 4.4 makes it even more complicated
    With the release of Android 4.4, Google has replaced the default WebView with a new WebView based on Chrome 30. While this may not have much impact on Nexus devices — it already uses Chrome as the default browser — it does matter to vendors that still ship the Android browser.On those devices the Android browser will suddenly be using the rendering engine from Chrome 30, which is an enormous improvement.

    THE GOOD NEWS

  • REMOTE DEBUGGING
  • Finally we have the ability to debug remotely Android native webviews –including PhoneGap apps- and the Android Browser and it works smoothly both from real devices and from the emulator. When we have an Android app opened with a web view or the Android Browser, the Chrome remote debugger tools will recognize it as a “Chrome 30” session and we have the full package of excellent tools for debug, profile and test our webapps.

    Untitled2

    For more info :

    https://blogs.oracle.com/fusionmiddleware/entry/developer_s_corner_developing_mobile
    http://tilomitra.com/web-vs-native/
    http://www.smashingmagazine.com/2013/10/17/best-of-both-worlds-mixing-html5-native-code/
    https://software.intel.com/en-us/html5/articles/building-cross-platform-apps-with-html5
    View story at Medium.com
    http://www.mobilexweb.com/blog/android-4-4-kitkat-browser-chrome-webview

    And you thought you knew Java Multithreading

    You think you can “Stop” a “Thread”

    In Java, there is no way to quickly and reliably stop a thread.
    Once you start a thread, nothing can (safely) stop it, except the thread itself. At most, the thread could be simply asked – or interrupted – to stop itself.

    Hence in Java, stopping threads is a two step procedure:

    • Sending stop signal to thread – aka interrupting it
    • Designing threads to act on interruption

    Interrupting a Thread

    If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn’t interrupt the thread but sets the interrupt flag to true. Let’s first see the methods provided by the Thread class for thread interruption.

    • public void interrupt()

    A thread in Java could be interrupted by calling `Thread.interrupt()` method.
    an interrupt() will either throw an InterruptedException (if the thread is executing a method which permits this, like sleep() or wait()), or it sets the isInterrupted() status of the thread – but not both. (If you catch an InterruptedException, you’re supposed to be able to figure out that this means the thread was interrupted, without needing to check the isInterrupted() method.)

    • Designing threads to act on interruption
    • public static boolean interrupted()

    The interrupted() is a static method in Thread class that determines if the current thread has been interrupted. “The interrupted status of the thread is cleared by this method”. Therefore, if a thread was interrupted, calling interrupted() once would return true, while a second call to it would return false until the current thread is interrupted again.

    • public boolean isInterrupted()

    The isInterrupted() is an instance method that tests if this thread instance has been interrupted. “The interrupted status of the thread is unaffected by this method”.

    isInterrupted() method returns true if the internal interrupted flag is set for the thread, or false otherwise.
    When you want to interrupt a thread, you need to have a reference to it, ie, a variable that holds a reference to the thread you want to interrupt. Say I have a variable myThread of type Thread, that contains a reference to the thread I want to interrupt. I can now interrupt that thread by calling
    myThread.interrupt();
    What does this do to the called thread? Like I mentioned above, this sets the internal interrupted flag for the thread. Now if I have code in the myThread Thread that calls isInterrupted(), it will return true.
    the other method, interrupted() is similar to isInterrupted() in that it returns the true/false status of the interrupted flag, EXCEPT it also clears the flag, so if you call interrupted() and it returns true, the very next time you call interrupted() it will return false, untill your thread is again interrupted. This method is useful when you are going to be interrupted a lot and you want to make sure you only handle each interruption one time, with a specific method for example.

    When an InterruptException is thrown, the interrupt is considered to be handled and the interrupted flag is cleared.
    The Thread.interrupted() static method is used in code that should be interruptable but does not normally wait() or sleep() – for instance, I/O or a lengthy calculation. For instance, you could use :

    ...
    if (Thread.interrupted()) {
       throw new InterruptException();
    }
    ...
    

    at a suitable point in your loop, and handle the exception in the usual way. The interrupted() method, too, clears the interrupt flag because the interrupt is considered to be handled.
    Finally, there is the Thread.isInterrupted() instance method. This is primarily a way for other threads to see if the thread has an unhandled interrupt, but it can also be used by a thread to look at its own interrupted status without clearing the flag (Thread.currentThread().isInterrupted()).

    Usefulness of the Thread.interrupted() method :

    I think you have a problem with it because it checks the current thread to see if it is interrupted. I guess you think there is a problem with that because if the Thread is interrupted how could it be executing to the point where it would be able to check if it was interrupted?

    This all comes down to understanding what ‘interrupting’ a Thread is. Interrupting a Thread isn’t causing it to stop execution, and it doesn’t necessarily mean it throws an exception either. If you read the JavaDocs for Thread#interrupt() you will see that, except for a few specific situations, all that method does is set a status flag. You should think of it as a ‘request to interrupt’. Your job, as a Thread-savvy programmer is to react to those requests when appropriate, and to respond to the interruption requests is to periodically check on the interrupted status of the Thread you are running in. There are two ways to do it – First you could get a reference to the current thread and check the isInterrupted() flag, and second you could call the static Thread.interrupted() method (as Muhammad said there is a difference in how the two methods function). Once you detect that an interrupt has been requested you can then react to it in a clean and orderly way.

    As the JavaDocs state, certain code, like wait() and Thread.sleep() will check the interrupted status flag and react by throwing an exception, others will react in other ways. But if you have code that runs in its own Thread and has a continuous or long lived loop then it is often a good idea to make sure your code reacts to the interruption itself.

    Example :

    public static void main(String[] args) throws Exception {
    
            /**
             * A Thread which is responsive to Interruption.
             */
            class ResponsiveToInterruption extends Thread {
                @Override public void run() {
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println("[Interruption Responsive Thread] Alive");
                    }
                    System.out.println("[Interruption Responsive Thread] bye**");
    
                }
            }
    
            /**
             * Thread that is oblivious to Interruption. It does not even check it's
             * interruption status and doesn't even know it was interrupted.
             */
            class ObliviousToInterruption extends Thread {
                @Override public void run() {
                    while (true) {
                        System.out.println("[Interruption Oblivious Thread] Alive");
                       // Restore the interrupted status
                       //Thread.currentThread().interrupt();
                    }
                    // The statement below will never be reached.
                    //System.out.println("[Interruption Oblivious Thread] bye");
                }
            }
    
            Thread theGood = new ResponsiveToInterruption();
            Thread theUgly = new ObliviousToInterruption();
    
            theGood.start();
            theUgly.start();
    
            theGood.interrupt(); // The thread will stop itself
            theUgly.interrupt(); // Will do nothing
    }
    
    <strong>O/P :</strong>
    [Interruption Oblivious Thread] Alive
    [Interruption Responsive Thread] Alive
    [Interruption Responsive Thread] Alive
    [Interruption Oblivious Thread] Alive
    [Interruption Responsive Thread] bye**
    [Interruption Oblivious Thread] Alive
    [Interruption Oblivious Thread] Alive
    [Interruption Oblivious Thread] Alive
    [Interruption Oblivious Thread] Alive
    ....
    

    Dealing with InterruptedException
    If throwing InterruptedException means that a method is a blocking method, then calling a blocking method means that your method is a blocking method too, and you should have a strategy for dealing with InterruptedException. Often the easiest strategy is to throw InterruptedException yourself, as shown in the putTask() and getTask() methods in Listing 1. Doing so makes your method responsive to interruption as well and often requires nothing more than adding InterruptedException to your throws clause.
    Listing 1. Propagating InterruptedException to callers by not catching it

    
    public class TaskQueue {
        private static final int MAX_TASKS = 1000;
    
        private BlockingQueue<Task> queue
            = new LinkedBlockingQueue<Task>(MAX_TASKS);
    
        public void putTask(Task r) throws InterruptedException {
            queue.put(r);
        }
    
        public Task getTask() throws InterruptedException {
            return queue.take();
        }
    }
    

    Don’t swallow interrupts
    Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can’t rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to “reinterrupt” the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don’t rethrow it, reinterrupt the current thread before returning.
    Restoring the interrupted status after catching InterruptedException :

    
    public class TaskRunner implements Runnable {
        private BlockingQueue<Task> queue;
    
        public TaskRunner(BlockingQueue<Task> queue) {
            this.queue = queue;
        }
    
        public void run() {
            try {
                 while (true) {
                     Task task = queue.take(10, TimeUnit.SECONDS);
                     task.execute();
                 }
             }
             catch (InterruptedException e) {
                 // Restore the interrupted status
                 Thread.currentThread().interrupt();
             }
        }
    }
    

    The worst thing you can do with InterruptedException is swallow it — catch it and neither rethrow it nor reassert the thread’s interrupted status. The standard approach to dealing with an exception you didn’t plan for — catch it and log it — also counts as swallowing the interruption because code higher up on the call stack won’t be able to find out about it. (Logging InterruptedException is also just silly because by the time a human reads the log, it is too late to do anything about it.) Listing 4 shows the all-too-common pattern of swallowing an interrupt:

    Swallowing an interrupt — don’t do this :

    
    // Don't do this
    public class TaskRunner implements Runnable {
        private BlockingQueue<Task> queue;
    
        public TaskRunner(BlockingQueue<Task> queue) {
            this.queue = queue;
        }
    
        public void run() {
            try {
                 while (true) {
                     Task task = queue.take(10, TimeUnit.SECONDS);
                     task.execute();
                 }
             }
             catch (InterruptedException swallowed) {
                 /* DON'T DO THIS - RESTORE THE INTERRUPTED STATUS INSTEAD */
             }
        }
    }
    

    If you cannot rethrow InterruptedException, whether or not you plan to act on the interrupt request, you still want to reinterrupt the current thread because a single interruption request may have multiple “recipients.” The standard thread pool (ThreadPoolExecutor) worker thread implementation is responsive to interruption, so interrupting a task running in a thread pool may have the effect of both canceling the task and notifying the execution thread that the thread pool is shutting down. If the task were to swallow the interrupt request, the worker thread might not learn that an interrupt was requested, which could delay the application or service shutdown.

    More info :
    http://www.ibm.com/developerworks/library/j-jtp05236/

    Your program dies with “main” thread

    main thread is not really main(adjective) it is just main(noun).

    When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

    • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
    • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

    The java program terminates when all non-daemon threads has been terminated ,it doesn’t have to be the main thread.or when System.exit() or Runtime.exit() is invoked.

    You can throw and catch checked exception from a thread

    The thread can’t throw the exception to any other thread (nor to the main thread). and you cannot make the inherited run() method throw any checked exceptions since you can only throw less than the inherited code, not more.
    Code in below catch block won’t work :

    package test.exec;
    
    public class TestThrdException {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		Thread myThread = new MyThread();
    		try {
    			myThread.start();
    		} catch (Exception e) {
    			System.out.println("Exception Catched");
    			e.printStackTrace();
    		}
    	}
    
    }
    
    class MyThread extends Thread {
    	public void run() {
    		throw new RuntimeException();
    	}
    }
    

    So what can you do ??

    Use Callable :
    To be able to send the exception to the parent thread, you can put your background thread in a Callable (it allows throwing also checked exceptions) which you then pass to the submit method of some Executor. The submit method will return a Future which you can then use to get the exception (its get method will throw an ExecutionException which contains the original exception).

    Wait and notify :

    public class ThingRunnable implements Runnable {
        private SomeListenerType listener;
        // assign listener somewhere
    
        public void run() {
            try {
                while(iHaveMorePackets()) {
                    doStuffWithPacket();
                }
            } catch(Exception e) {
                listener.notifyThatDarnedExceptionHappened(...);
            }
        }
     }
    

    The coupling comes from an object in the parent thread having to be of type SomeListenerType.

    Use UncaughtExceptionHandler :

    package test.exec;
    
    public class TestThrdException {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		Thread myThread = new MyThread();
    		// Add the handler to the thread object
    		myThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    
    			@Override
    			public void uncaughtException(Thread t, Throwable e) {
    
    				System.out.println("ERROR! An exception occurred in " + t.getName() + ". Cause: " + e.getMessage());
    			}
    		});
    		myThread.start();
    	}
    }
    
    class MyThread extends Thread {
    	public void run() {
    		throw new RuntimeException();
    	}
    }
    
    

    Java : Executor framework

    “Thread” to “Thread per Request” to “Thread Pool” :

    Single Thread :
    1Thread

    Single thread has an ability to handle only one user a time. The other users must wait in queue until the working user finished his or her task.
    If we consider about CPU and I/O usage, single thread is not fully utilized because while CPU is busy I/O usually is free and vice versa.

     Advantage
    • Straight forward
    • Easy to develop

    Disadvantage
    • Waste time.
    • CPU and I/O are not fully utilized

    Thread per Request :
    ThrdPerReq
    Thread per request or connection has been introduced in order to maximize the system resource and provide responsiveness to users which single thread is not capable. Thread per request or connection architecture will create a thread for each request from a client. In other words, system can create a number of threads as per request. The only limitation is software and hardware capacity.

    Advantage
    • No waiting users
    • Maximize system resources
    • It is a little hard to develop unless you follow the guideline strictly

    Disadvantage
    • A lot of overhead in creating and destroying threads for many requests or connections
    • Server might crash if the number of requests is beyond the server’s capacity

    Thread Pool :
    ThrdPool
    Thread pool pre-defines a number of thread running in its pool. Let’s say we have 2 threads in the pool, then the system is capable of serving only 2 requests at the same time. Other requests must wait in queue until the 2 threads in the pool finish their work.

    Advantage
    • By optimal number of thread in the pool, the chance of server crash is highly reduced
    • Has little request in queue

    Disadvantage
    • Must do performance tuning for specific hardware capacity
    • Difficult to develop until you take advantage of Java concurrency package

    Risks of using thread pools
    (http://www.ibm.com/developerworks/java/library/j-jtp0730.html)

    While the thread pool is a powerful mechanism for structuring multithreaded applications, it is not without risk. Applications built with thread pools are subject to all the same concurrency risks as any other multithreaded application, such as synchronization errors and deadlock, and a few other risks specific to thread pools as well, such as pool-related deadlock, resource thrashing, and thread leakage.

    Deadlock
    With any multithreaded application, there is a risk of deadlock. A set of processes or threads is said to be deadlocked when each is waiting for an event that only another process in the set can cause.

    More info :

    https://myshadesofgray.wordpress.com/2012/10/06/deadlock-detection-in-java/

    Resource thrashing
    If the thread pool size is not tuned properly threads consume numerous resources, including memory and other system resources. While the scheduling overhead of switching between threads is small, with many threads context switching can become a significant drag on your program’s performance.

    Concurrency errors
    Thread pools and other queuing mechanisms rely on the use of wait() and notify() methods, which can be tricky. If coded incorrectly, it is possible for notifications to be lost, resulting in threads remaining in an idle state even though there is work in the queue to be processed. Great care must be taken when using these facilities.

    Thread leakage
    A significant risk in all kinds of thread pools is thread leakage, which occurs when a thread is removed from the pool to perform a task, but is not returned to the pool when the task completes. One way this happens is when the task throws a RuntimeException or an Error. If the pool class does not catch these, then the thread will simply exit and the size of the thread pool will be permanently reduced by one. When this happens enough times, the thread pool will eventually be empty, and the system will stall because no threads are available to process tasks.
    Tasks that permanently stall, such as those that potentially wait forever for resources that are not guaranteed to become available or for input from users who may have gone home, can also cause the equivalent of thread leakage.

    Request overload
    It is possible for a server to simply be overwhelmed with requests. In this case, we may not want to queue every incoming request to our work queue, because the tasks queued for execution may consume too many system resources and cause resource starvation. It is up to you to decide what to do in this case; in some situations, you may be able to simply throw the request away, relying on higher-level protocols to retry the request later, or you may want to refuse the request with a response indicating that the server is temporarily busy.

    So No need to write your own

    In early versions of Java (1.4 or earlier), developers needed to implement concurrent applications—including thread pool logic—themselves using low-level language constructs and the Java Thread API. The results were often poor. The nature of the Java Thread API often led unwitting programmers to develop code that introduced hard-to-debug programming errors.
    In Java 5.0, Sun introduced the Java concurrency utilities (JSR-166) to address these issues and provide a standard set of APIs to create concurrent applications.

    Introduction to Java Executor Framework

    Ruannable vs Callable<T>
    The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

    Runnable Callable<T>
    Introduced in Java 1.0 Introduced in Java 1.5 as part of java.util.concurrent library
    Runnable cannot be parametrized Callable is a parametrized type whose type parameter indicates the return type of its run method
    Classes implementing Runnable needs to implement run() method Classes implementing Callable needs to implement call() method
    Runnable.run() returns no Value Callable.call() returns a value of Type T
    Can not throw Checked Exceptions Can throw Checked Exceptions
    publicinterfaceRunnable {void run();} publicinterfaceCallable<V>{    V call()throwsException;}

     

    Note :

    In order to convert Runnable to Callable use the following utility method provided by Executors class

    Callable callable = Executors.callable(Runnable task); 

    Callable, however must be executed using a ExecutorService instead of Thread as shown below.

    result = exec.submit(aCallable).get(); 

     

    Thread Pool and Executor

    Java 5.0 comes with its own thread pool implementation – within the Executor and ExecutorService interfaces. This makes it easier for you to use thread pools within your own programs.

    executor

     

    The java.util.concurrent package defines three executor interfaces:

    The Executor Interface

    The Executor interface provides a single method, execute, designed to be a drop-in replacement for a common thread-creation idiom. If r is a Runnable object, and e is anExecutor object you can replace

    (new Thread(r)).start();

    with

    e.execute(r);

    However, the definition of execute is less specific. The low-level idiom creates a new thread and launches it immediately. Depending on the Executor implementation,execute may do the same thing, but is more likely to use an existing worker thread to run r, or to place r in a queue to wait for a worker thread to become available. (We’ll describe worker threads in the section on Thread Pools.)

    The executor implementations in java.util.concurrent are designed to make full use of the more advanced ExecutorService and ScheduledExecutorServiceinterfaces, although they also work with the base Executor interface.

     

    The ExecutorService Interface

    The ExecutorService interface supplements execute with a similar, but more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts Callable objects, which allow the task to return a value. The submit method returns a Future object, which is used to retrieve the Callable return value and to manage the status of both Callable and Runnable tasks.

    ExecutorService also provides methods for submitting large collections of Callable objects. Finally, ExecutorService provides a number of methods for managing the shutdown of the executor. To support immediate shutdown, tasks should handle interrupts correctly.

    exec1

    Executor is the root interface with a single execute method. Anything that implements a Runnable interface can passed as a parameter. Silly Executor, however, has no support for Callable though.

     

    exec2

    The ScheduledExecutorService Interface

    The ScheduledExecutorService interface supplements the methods of its parent ExecutorService with schedule, which executes a Runnable or Callable task after a specified delay. In addition, the interface defines scheduleAtFixedRate and scheduleWithFixedDelay, which executes specified tasks repeatedly, at defined intervals.

    Creating and Managing ThreadPool in Java :

    Managing thread life cycle is expensive and that is how Executors came into picture. In complicated or real life applications, allocating and deallocating memory to multiple threads becomes even more complicated (compared to single thread). So to handle this Java introduced concept of thread pools.

    Thread pool consists of worker threads. Tasks are submitted to a thread pool via a queue. Worker threads have a simple life : request new task from a work queue, execute it, and go back to pool for assignment to next task.

    Executors class provides factory methods to create thread pools and return executor.

    ThreadPool creations and management in java can be handled in two ways :

    Using Executors utility Class  factory methods:

    • ExecutorService newCachedThreadPool() creates a thread pool that creates new threads as needed, but which reuses previously constructed threads when they’re available. Threads that haven’t been used for 60 seconds are terminated and removed from the cache. This thread pool typically improves the performance of programs that execute many short-lived asynchronous tasks.
    • ExecutorService newSingleThreadExecutor() creates an executor that uses a single worker thread operating off an unbounded queue — tasks are added to the queue and execute sequentially (no more than one task is active at any one time). If this thread terminates through failure during execution before shutdown of the executor, a new thread will be created to take its place when subsequent tasks need to be executed.
    • ExecutorService newFixedThreadPool(int nThreads) creates a thread pool that re-uses a fixed number of threads operating off a shared unbounded queue. At mostnThreads threads are actively processing tasks. If additional tasks are submitted when all threads are active, they wait in the queue until a thread is available. If any thread terminates through failure during execution before shutdown, a new thread will be created to take its place when subsequent tasks need to be executed. The pool’s threads exist until the executor is shut down.

    The Executor framework offers additional types (such as theScheduledExecutorService interface).

    Creating customized thread pool executor :

    If none of the executors provided by the above factory methods meet your needs, constructing instances of java.util.concurrent.ThreadPoolExecutor or

    java.util.concurrent.ScheduledThreadPoolExecutor will give you additional options.

    The ThreadPoolExecutor has several constructors available. For instance:

    
    int  corePoolSize  =    5;
    
    int  maxPoolSize   =   10;
    
    long keepAliveTime = 5000;
    
    ExecutorService threadPoolExecutor =        new ThreadPoolExecutor(                corePoolSize,                maxPoolSize,                keepAliveTime,                TimeUnit.MILLISECONDS,                new LinkedBlockingQueue<Runnable>()                );
    
    

    However, unless you need to specify all these parameters explicitly for your ThreadPoolExecutor, it is often easier to use one of the factory methods in the java.util.concurrent.Executors class.

    Future Results

    When you ask an executor service to run a callable object, the service returns a Future object that allows you to retrieve those results, monitor the status of the task, and cancel the task. TheFuture interface looks like this:

    </pre>
    <pre>
    public interface Future<V> { V get( ) throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; boolean isDone( ); boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled( ); }</pre>
    <pre>

    Callable and future objects have a one-to-one correspondence: every callable object that is sent to an executor service returns a matching future object. The get() method of the future object returns the results of its corresponding call( ) method. The get() method blocks until the call() method has returned (or until the optional timeout has expired). If the call() method throws an exception, the get() method throws an ExecutionException with an embedded cause, which is the exception thrown by the call( ) method.

    The future object keeps track of the state of an embedded Callable object. The state is set to cancelled when thecancel() method is called. When the call() method of a callable task is called, the call() method checks the state: if the state is cancelled, the call() method immediately returns.

    When the cancel() method is called, the corresponding callable object may be in one of three states. It may be waiting for execution, in which case its state is set to cancelled and the call() method is never executed. It may have completed execution, in which case the cancel( ) method has no effect. The object may be in the process of running. In that case, if the mayInterruptIfRunning flag is false, the cancel() method again has no effect.

    If the mayInterruptIfRunning flag is true, however, the thread running the callable object is interrupted. The callable object must still pay attention to this, periodically calling the Thread.interrupted() method to see if it should exit.

    When an object in a thread pool is cancelled, there is no immediate effect: the object still remains queued for execution. When the thread pool is about to execute the object, it checks the object’s internal state, sees that it has been cancelled, and skips execution of the object. So, cancelling an object on a thread pool queue does not immediately make space in the thread pool’s queue. Future calls to the execute() method may still be rejected, even though cancelled objects are on the thread pool’s queue: the execute() method does not check the queue for cancelled objects.

    One way to deal with this situation is to call the purge() method on the thread pool. The purge() method looks over the entire queue and removes any cancelled objects. One caveat applies: if a second thread attempts to add something to the pool (using the execute() method) at the same time the first thread is attempting to purge the queue, the attempt to purge the queue fails and the canceled objects remain in the queue.

    A better way to cancel objects with thread pools is to use the remove() method of the thread pool, which immediately removes the task from the thread pool queue. The remove() method can be used with standard runnable objects.

    The FutureTask Class

    You can associate a Runnable object with a future result using the FutureTask class:

    </pre>
    <pre>public class FutureTask<V> implements Future<V>, Runnable {}</pre>
    <pre>

    This class is used internally by the executor service: the object returned from the submit() method of an executor service is an instance of this class. However, you can use this class directly in programs as well. This makes sense when you need to monitor the status of a runnable object within an executor: you can construct a future task with an embedded runnable object and send the future task to the execute() method of an executor (or an executor service). You can then use the methods of the Future interface to monitor the status of the run() method of the embedded runnable object.

    FutureTask object can hold either an embedded runnable or callable object, depending on which constructor is used to instantiate the object:

    </pre>
    <pre>public FutureTask(Callable<V> task); public FutureTask(Runnable task, V result);</pre>
    <pre>

    The get() method of a future task that embeds a callable task returns whatever is returned by the call( ) method of that embedded object. The get() method of a future task that embeds a runnable object returns whatever object was used to construct the future task object itself

     

    Algorithm for using an Executor

    1. Create an Executor

    You first create an instance of an Executor or ExecutorService in some global context (such as the application context for a servlet container).

    The Executors class has a number of convenience static factory methods that create an ExecutorService. For instance, newFixedThreadPool() returns a ThreadPoolExecutor instance which is intialized with an unbounded queue and a fixed number of threads; while newCachedThreadPool() returns a ThreadPoolExecutor instance initialized with an unbounded queue and unbounded number of threads. In the latter case, existing threads are reused if available, and if no free thread is available, a new one is created and added to the pool. Threads that have been idle for longer than a timeout period will be removed from the pool.

    private static final Executor executor = Executors.newFixedThreadPool(10);
    Rather than use these convenience methods, you might find it more appropriate to instantiate your own fully customized version of ThreadPoolExecutor – using one of its many constructors.

    private static final Executor executor = new ThreadPoolExecutor(10, 10, 50000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(100));
    This creates a bounded queue of size 100, with a thread pool of fixed size 10.

    2. Create one or more tasks

    You are required to have one or more tasks to be performed as instances of either Runnable or Callable.

    3. Submit the task to the Executor

    Once you have an ExecutorService, you can submit a task to it using either the submit() or execute() methods, and a free thread from the pool will automatically dequeue the tasks and execute it.
    Methods in Executor Service
    There are a few different ways to delegate tasks for execution to an ExecutorService:
    • execute(Runnable)
    • submit(Runnable)
    • submit(Callable)
    • invokeAny(…)
    • invokeAll(…)

    Take a look at each of these methods in the following sections.

    execute(Runnable)
    The execute(Runnable) method takes a java.lang.Runnable object, and executes it asynchronously. Here is an example of executing a Runnable with an ExecutorService:

    
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    
    executorService.execute(new Runnable() {
        public void run() {
            System.out.println("Asynchronous task");
        }
    });
    
    executorService.shutdown();
    
    

    There is no way of obtaining the result of the executed Runnable, if necessary. You will have to use a Callable for that (explained in the following sections).

    submit(Runnable)
    The submit(Runnable) method also takes a Runnable implementation, but returns a Future object. ThisFuture object can be used to check if the Runnable as finished executing.
    Here is a ExecutorService submit() example:

    
    Future future = executorService.submit(new Runnable() {
        public void run() {
            System.out.println("Asynchronous task");
        }
    });
    
    future.get();  //returns null if the task has finished correctly.
    
    

    submit(Callable)
    The submit(Callable) method is similar to the submit(Runnable) method except for the type of parameter it takes. The Callable instance is very similar to a Runnable except that its call() method can return a result. TheRunnable.run() method cannot return a result.
    The Callable’s result can be obtained via the Future object returned by the submit(Callable) method. Here is an ExecutorService Callable example:

    
    Future future = executorService.submit(new Callable(){
        public Object call() throws Exception {
            System.out.println("Asynchronous Callable");
            return "Callable Result";
        }
    });
    
    System.out.println("future.get() = " + future.get());
    
    

    The above code example will output this:

    Asynchronous Callable
    future.get() = Callable Result
    
    

    The invokeAny() method takes a collection of Callable objects, or subinterfaces of Callable. Invoking this method does not return a Future, but returns the result of one of the Callable objects. You have no guarantee about which of the Callable’s results you get. Just one of the ones that finish.
    If one of the tasks complete (or throws an exception), the rest of the Callable’s are cancelled.
    Here is a code example:

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    
    Set<Callable<String>> callables = new HashSet<Callable<String>>();
    
    callables.add(new Callable<String>() {
        public String call() throws Exception {
            return "Task 1";
        }
    });
    callables.add(new Callable<String>() {
        public String call() throws Exception {
            return "Task 2";
        }
    });
    callables.add(new Callable<String>() {
        public String call() throws Exception {
            return "Task 3";
        }
    });
    
    String result = executorService.invokeAny(callables);
    
    System.out.println("result = " + result);
    
    executorService.shutdown();
    
    

    This code example will print out the object returned by one of the Callable’s in the given collection. I have tried running it a few times, and the result changes. Sometimes it is “Task 1”, sometimes “Task 2” etc.

    invokeAll()
    The invokeAll() method invokes all of the Callable objects you pass to it in the collection passed as parameter. The invokeAll() returns a list of Future objects via which you can obtain the results of the executions of eachCallable.
    Keep in mind that a task might finish due to an exception, so it may not have “succeeded”. There is no way on aFuture to tell the difference.
    Here is a code example:

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    
    Set<Callable<String>> callables = new HashSet<Callable<String>>();
    
    callables.add(new Callable<String>() {
        public String call() throws Exception {
            return "Task 1";
        }
    });
    callables.add(new Callable<String>() {
        public String call() throws Exception {
            return "Task 2";
        }
    });
    callables.add(new Callable<String>() {
        public String call() throws Exception {
            return "Task 3";
        }
    });
    
    List<Future<String>> futures = executorService.invokeAll(callables);
    
    for(Future<String> future : futures){
        System.out.println("future.get = " + future.get());
    }
    
    executorService.shutdown();
    
    

    the only difference being that all the flavors of submit() returns a Future that can be used to query the result of the submitted task execution.
    On the other hand, execute() does not return a Future.
    There is no difference in the implementation and in fact submit() internally calls execute().

    4. Execute the task and getting the result
    As soon as we invoke the submit() method of ExecutorService the Callable are handed over to ExecutorService to execute. Here one thing we have to note, the submit() is not blocking. So, all of our Callables will be submitted right away to the ExecutorService, and ExecutorService will decide when to execute which callable. For each Callable we get a Future object to get the result later.
    Once the Callables are submitted for execution, we are iterating through all Futures to get the result of execution. We are invoking the get() method of Future to get the result. Here we have to remember that, the get() is a blocking method. So the first invocation of get() will wait until that Callable is finished. Once we receive the result of the execution of first Callable it will wait for next Callable to finish, and so on. Since the get() is blocking, we could put the iteration on a separate thread to continue the execution, and get the result later when all Futures are ready with their results.

    There is also, another useful method named isDone() on Future which let us check if the Callable for that Future is finished or not.

    5. Shutdown the Executor
    When you are done using the ExecutorService you should shut it down, so the threads do not keep running.
    For instance, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExexutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.
    To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorServicewill not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.
    If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

    Example :
    With Runnable :

    package test.exec;
    
    public class MyRunnable implements Runnable {
    	private final long countUntil;
    
    	MyRunnable(long countUntil) {
    		this.countUntil = countUntil;
    	}
    
    	@Override
    	public void run() {
    		long sum = 0;
    		System.out.println(Thread.currentThread().getName()+" : Start");
    		for (long i = 1; i < countUntil; i++) {
    			sum += i;
    		}
    		System.out.println(Thread.currentThread().getName() +" : "+ sum+" : End");
    	}
    }
    
    package test.exec;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class RunnableExecMain {
    	private static final int NTHREDS = 10;
    
    	public static void main(String[] args) {
    		ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    		for (int i = 0; i < 500; i++) {
    			Runnable worker = new MyRunnable(10000000L + i);
    			executor.execute(worker);
    		}
    		// This will make the executor accept no new threads
    		// and finish all existing threads in the queue
    		executor.shutdown();
    		// Wait until all threads are finish
    		while (!executor.isTerminated()) {
    		}
    		System.out.println("Finished all threads");
    	}
    }
    
    

    With Callable :

    package test.exec;
    
    import java.util.concurrent.Callable;
    
    public class MyCallable implements Callable<Long> {
    	@Override
    	public Long call() throws Exception {
    		long sum = 0;
    		for (long i = 0; i <= 100; i++) {
    			sum += i;
    		}
    		return sum;
    	}
    
    }
    package test.exec;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class CallableExecMain {
    	private static final int NTHREDS = 10;
    
    	public static void main(String[] args) {
    
    		ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    		List<Future<Long>> list = new ArrayList<Future<Long>>();
    		for (int i = 0; i < 20000; i++) {
    			Callable<Long> worker = new MyCallable();
    			Future<Long> submit = executor.submit(worker);
    			list.add(submit);
    		}
    		long sum = 0;
    		System.out.println(list.size());
    		// now retrieve the result
    		for (Future<Long> future : list) {
    			try {
    				sum += future.get();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			} catch (ExecutionException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.println(sum);
    		executor.shutdown();
    		// Wait until all threads are finish
    		while (!executor.isTerminated()) {
    		}
    		System.out.println("Finished all threads");
    	}
    }