Monday 23 January 2017

What is an Immutable Class ? How to create Immutable class ? What are the advantage of Immutability ? Why is it important in multi-threading context ? Can you write a Custom immutable class ? What are semantics for writing an Immutable Class in java ?

In this article we will discuss  about following  topic
è What is an Immutable Class ?
è How to create Immutable class ?
è Write a Custom immutable class ?
è What are the advantage of  Immutability ?
è Why is it important in multi-threading context ?
è What are semantics for writing an Immutable Class in java ?

What is an Immutable Class ?
As per Oracle docs , An Immutable class is a class if its state of object  cannot change after it is constructed. It means any modification of  Immutable object will be another immutable object.  Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.All wrapper classes in java.lang are immutable  String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.

Read this article :

Why is String immutable?


Example of  Immutable class:
·         java.lang.String
·         The wrapper classes for the primitive types: java.lang.Integer, java.lang.Byte, java.lang.Character, java.lang.Short, java.lang.Boolean, java.lang.Long, java.lang.Double, java.lang.Float
·         java.lang.StackTraceElement (used in building exception stacktraces)
·         Most enum classes are immutable, but this in fact depends on the concrete case. (Don't implement mutable enums, this will screw you up somewhen.) I think that at least all enum classes in the standard API are in fact immutable.
·         java.math.BigInteger and java.math.BigDecimal (at least objects of those classes themselves, subclasses could introduce mutability, though this is not a good idea)
·         java.io.File. Note that this represents an object external to the VM (a file on the local system), which may or may not exist, and has some methods modifying and querying the state of this external object. But the File object itself stays immutable. (All other classes in java.io are mutable.)
·         java.awt.Font - representing a font for drawing text on the screen (there may be some mutable subclasses, but this would certainly not be useful)
·         java.awt.BasicStroke - a helper object for drawing lines on graphic contexts
·         java.awt.Color - (at least objects of this class, some subclasses may be mutable or depending on some external factors (like system colors)), and most other implementations of java.awt.Paint .
How to create Immutable class ?
The steps to create a Immutable class  in Java  -
1)    Mark the class final .
2)    Mark the fields private and final.
3)    Set the values of properties of the class final and Private , i.e do not  use any setter methods,.
4)    Do not change the state of  the objects in any methods of  the class. If the instance fields includes references to mutable objects, don’t allow those objects to be changed.
5)    Don’t provide methods that modified the mutable objects.
6)    Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
Write a Custom immutable class ?

Example of  Immutable class in Java:

package Java91.blogspot.in;

public final class TestImmutableClass {
       private final Integer id;
       private final String name;
       private final String password;

       public TestImmutableClass(Integer id, String name, String password) {
              super();
              this.id = id;
              this.name = name;
              this.password = password;
       }
      
       public Integer getId() {
              return id;
       }

       public String getName() {
              return name;
       }

       public String getPassword() {
              return password;
       }
}
What are the advantage of  Immutability ?
1.     Immutable objects are thread-safe so you will not have any synchronization issues.
2.     Immutable objects are good Map keys and Set elements, since these typically do not change once created.
3.     Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
4.     Immutability makes it easier to parallelize your program as there are no conflicts among objects.
5.     The internal state of your program will be consistent even if you have exceptions.
6.     References to immutable objects can be cached as they are not going to change.
In Java the good programming practice is one should try to use immutable objects as far as possible. Immutability can have a performance cost, since when an object cannot be mutated we need to copy it if we want to write to it.
By Joshua Bloch
Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible.
Why is it important in multi-threading context ?
As we all know if an object is  Immutable , it is thread safe. But some scenario It is not thread safe . I am going to explain why Immutable class not fully thread safe .
Let look into the  String class code:
public class String {
       private final char value[];
       /** Cache the hash code for the string */
       private int hash; // Default to 0

       public String(char[] value) {
              this.value = Arrays.copyOf(value, value.length);
       }

       public int hashCode() {
              int h = hash;
              if (h == 0 && value.length > 0) {
                     char val[] = value;
                     for (int i = 0; i < value.length; i++) {
                           h = 31 * h + val[i];
                     }
                     hash = h;
              }
              return h;
       }
}
String is considered immutable. Looking at its implementation, we can deduce one thing: an immutable string can change its internal state (in this case, the hashcode which is lazy loaded) as long as it is not externally visible.Now I am going to rewrite the hashcode method in a non-thread safe way:
public int hashCode() {
    if (hash == 0 && value.length > 0) {
        char val[] = value;
        for (int i = 0; i < value.length; i++) {
            hash = 31 * hash + val[i];
        }
    }
    return hash;
}
As you can see, I have removed the local variable h and I have instead affected the variable hash directly. This implementation is NOT thread safe! If several threads call hashcode at the same time, the returned value could be different for each thread. The question is, 'is this class immutable?' Since two different threads can see a different hashcode, in an external point of view we have a change of state and so it is not immutable.We can so conclude that String is immutable because it is thread safe and not the opposite. So... What's the point of saying "Use an immutable object, it is thread-safe! But take care, you have to make your immutable object thread-safe!"?
What are semantics for writing an Immutable Class in java ?
1.     Immutable objects are thread-safe so you will not have any synchronization issues.
2.     Immutable objects are good Map keys and Set elements, since these typically do not change once created.
3.     Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
4.     Immutability makes it easier to parallelize your program as there are no conflicts among objects.
5.     The internal state of your program will be consistent even if you have exceptions.
6.     References to immutable objects can be cached as they are not going to change.

















Friday 20 January 2017

How does SOAP work?
·   SOAP is used to provide a UI that can be achieved from the client object and the request that it sends, goes to the server that can be achieved by using the server object.

·   The UI creates some files or methods that consists of server object and the name of the interface to the server object. It also consists of other information like name of the interface and method.

·   It uses HTTP to send the XML to the server using the POST method. The server parses the method and send the result to the client side.

·  The server creates more XML that consists of responses of the user interface’s request that is used using HTTP.

Describe the SOAP mustUnderstand attribute?
The SOAP mustUnderstand attribute can be used to indicate whether a header entry is mandatory or optional for the recipient to process. 

If you add mustUnderstand="1" to a child element of the Header element it indicates that the receiver processing the Header must recognize the element. If the receiver does not recognize the element it will fail when processing the Header.
Syntax>  soap:mustUnderstand="0|1"

What is the difference between a fault and exception in Apache SOAP?

The difference lies in where the error occurs - on the client side (during the generation of the soap request or the unmarshalling the response) - or on the server side (when un marshalling the request, processing the message or marshalling the response).
The client side raises an exception whereas the server side sends a SOAP response to the client indicating an error occurred on the server side.

Describe the SOAP encodingStyle Attribute?
The encodingStyle attribute is used to define the data types used in the document.

Explain about the actor element?
A SOAP message has to travel a very long distance between its client and server but during the process a part of the message may be intended to be deployed to another destination which is made possible by the SOAP elements actor attribute which address the header element to a particular location.



What happens if RestFull resources are accessed by multiple clients? Do you need to make it thread-safe?
Since a new Resource instance is created for every incoming Request there is no need to make it thread-safe or add synchronization. Multiple clients can safely access RestFull resources concurrently.

What types of Operations available in WSDL? What are the different standards protocols for Web Service? What is the difference between HTTP POST and PUT requests in REST?

What types of Operations available in WSDL?
·   One-way : The operation can receive a message but will not return a response

·  Request-response: The operation can receive a request and will return a response

·  Solicit-response: The operation can send a request and will wait for a response

·   Notification: The operation can send a message but will not wait for a response

What are the different standards protocols for Web Service?
·   XML-RPC is a remote procedure call (RPC) protocol which uses XML to encode its calls and HTTP as a transport mechanism. In XML-RPC objects or structures are exchanged between 2 applications.

·    JAX-RPC: Java API for XML-based RPC, JAX-RPC refers to Java API for XML-based RPC. It specify java technology for for web-based services and clients using RPC or remote procedure calls which are based on XML based protocol like SOAP.

·   JAX-WS: Java API for XML Web Services, which is part of Java EE Platform & Glassfish Project. It also provides annotation based Web Service.

·   JAX-RPC vs. JAX-WS:  JAX-WS replaced the JAX-RPC API in Java Platform, Enterprise Edition 5.It provides enhancement over JAX-RPC.

What is the difference between HTTP POST and PUT requests in REST?POST is used to create whereas PUT is used to (update, if does not exist create it)/ Replace.

Why SOAP Envelope ? What is XML-RPC?

SOAP Envelope

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
</soap:Header>

<soap:Body>
                <soap:Fault>
                </soap:Fault>
</soap:Body>
</soap:Envelope>

What is XML-RPC?
XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response.

Difference between an XML Schema and WSDL?

    XSD defines a schema which is a definition of how an XML document can be structured. You can use it to check that a given XML document is valid and follows the rules you've laid out in the schema.

·   WSDL is an XML document that describes a web service. It shows which operations are available and how data should be structured to send to those operations.

·   WSDL documents have an associated XSD that show what is valid to put in a WSDL document

WSDL Document Structure

WSDL document can be partitioned into two sections:

The abstract sections define SOAP messages in a platform and language independent manner. They don’t contain any machine or language specific elements. The abstract elements are types, message and portType

The concrete sections are site-specific, machine-specific or language-specific. The concrete elements are binding and service.

A WSDL document describes a web service using below major elements:








<definitions>
    <types>    definition of types........ </types>
    <message>  definition of a message.... </message> 
    <portType> definition of a port....... </portType>
    <binding>  definition of a binding.... </binding>
    <service>  definition of a service.... </service>
</definitions>



·         definitions: Must be the root element of all WSDL documents. It defines the name of the web service, declares namespaces used throughout the document and contains all other elements described ahead.

·         types: The <types> element defines the data types that are used by the web service.

·         message: Each message can consist of one or more parts. The parts can be compared to the parameters of a function call in a traditional programming language.

·         portType: It describes a web service, the operations that can be performed, and the messages that are involved .The <portType> element can be compared to a function library (or a module, or a class) in a traditional programming language

·         binding: The <binding> element defines the data format and protocol for each port type.

·         service: service element that makes it possible to group together the definitions of several web services in one single WSDL document.