What is Singleton pattern and it’s uses ?

Posted on Updated on

What is Singleton pattern and it’s uses ?

This is most frequently asked question in Java interview for freshers, their uses in developement. In this article we will discuss following topics :-

  • What is Singleton Pattern ?
  • How to implement in coding ?
  • How many possible way to create a Singleton object in Java.
  • What is double check in Singleton Pattern and advantage of it.

Singleton is a creation Design pattern, it’s used to control the initialization of Object and ensure that only one instance of Object will be created in the Java Virtual Machine.In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects

Key Points :-

  • Global access point, a scope of Singleton object is Global or an application level.

How to implement in coding ?

There are various way to implement singleton class in Java.

  1. Class-loader static initialization or Eager Loading
  2. synchronized or Lazy Loading
  3. Using Enum

Implementation with Class-loader static initialization or Eager Loading :-

In this case class loader initialized the Object instance at the time of loading and subsequently calling this method get same object reference. It slow the application start-up performance.

public class MyFactory {
  private static final MyFactory instance = new MyFactory();

  public static MyFactory getInstance() {
    return instance;
  }

  private MyFactory() {}
}

Implementation with Synchronized i.e Lazy loading:-

In this case, a thread calling this method getInstance() an Object will be created and second time onward all subsequently calling this method point to same reference.  This is also call on demand object creation.

public class MyFactory {
  private static MyFactory instance;

  public static synchronized MyFactory getInstance() {
    if (instance == null)
      instance = new MyFactory();
    return instance;
  }

  private MyFactory() {}
}

Implementation with Enum example:-

Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment

public Enum MyFactory {
  INSTANCE;
  private static final ConnectionFactory factory = new ConnectionFactory();

  public Connection getConnection() {
    return factory.getConnection();
  }
}

Question: Why can’t we use a static class instead of singleton?
Answer:

  • One of the key advantages of singleton over static class is that it supports inheritance.while the static class cannot
  • Another difference is that static class will have all its member as static only unlike Singleton.
  • Another advantage of Singleton is that it can be lazily loaded whereas static will be initialized whenever it is first loaded.
  • Singleton object stores in Heap but, static object stores in stack.
  • We can clone the object of Singleton but, we can not clone the static class object.
  • Singleton can use the Object Oriented feature of polymorphism but static class cannot.

Question: Can the singleton class be subclassed?

Answer: Frankly speaking singleton is just a design pattern and it can be subclassed. However it is worth to understand the logic or requirement behind subclassing a singleton class as the child class might not inherit the singleton pattern objective by extending the Singleton class. However the subclassing can be prevented by using the final keyword in the class declaration.

Question: Can there be multiple instance of singleton using cloning?
Answer: That was a good catch! What do we do now? To prevent the another instance to be created of the singleton instance we can throw exception from inside the clone() method.

Question: What is the impact if we are creating another instance of singleton using serialization and deserialization?
Answer: When we serialize a class and deserialize it then it creates another instance of the singleton class. Basically as many times as you deserialize the singleton instance it will create multiple instance. Well in this case the best way is to make the singleton as enum. In that way the underlying Java implementation takes care of all the details. If this is not possible then we will need to override the readobject() method to return the same singleton instance.

Question: Which other pattern works with Singleton?
Answer:There are several other pattern like Factory method, builder and prototype pattern which uses Singleton pattern during the implementation.

Question: Which classes in JDK uses singleton pattern?
Answer: java.lang.Runtime : In every Java application there is only one Runtime instance that allows the application to interface with the environment it is running. The getRuntime is equivalent to the getInstance() method of the singleton class.

 

Uses of Singleton design pattern:

Various usages of Singleton Patterns:

  • Hardware interface access: The use of singleton depends on the requirements. However practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock.
  • Logger : Similarly singleton is a good potential candidate for using in the log files generation. Imagine an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference.
  • Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file at the first time and there after from second call onwards the client applications read the data from in-memory objects.
  • Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object.

RESTful example with Tomcat and maven

Posted on Updated on

RESTful example with Tomcat and Maven

This is a Simple example of RESTful using jersey service in eclipse which is intended to explore how to implement RESTful services in our project. In web.xml file, Full qualified package is given to scan all services class under this package it will automatically happened at deployment time also servlet-mapping defined services mapping pattern in this case /rest/* means all RESTful container will be treated all services as RESTful service that start with /rest/*. example :-

  • /rest/user
  • /rest/user/{user_id}

Create and configure a pom.xml which contains all required dependencies for RESTful.

pom.xml file under root directory in your project:-


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<groupId>com.rest</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>RESTfulExample1</artifactId>
<name>RESTfulExample1</name>
<version>1.1-SNAPSHOT</version>
<packaging>war</packaging>

<description>
RESTful Example1
</description>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
<artifactId>jersey-container-servlet</artifactId>
<version>2.17</version>
</dependency>
<!-- Required only when you are using JAX-RS Client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.2.3</version>
</dependency>

</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>/web</warSourceDirectory>
<warName>RESTfulExample1</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>

<finalName>ITCM</finalName>
</build>
</project>


Project explorer in Eclipse : –

project-explorer

Project src files :-

com.rest.service

UserInfoService.Java :- Intended of this class is to produce and consume resources using RESTful service.


package com.rest.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.rest.model.User;
import com.rest.repository.UserRepository;

@Path("/user")
public class UserInfoService {
private UserRepository userRepo = new UserRepository();

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers(){
return Response.ok().entity(userRepo.getAllUsers()).build();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{user_id}")
public Response getUser(@PathParam("user_id") int user_id){
return Response.ok().entity(userRepo.getUser(user_id)).build();
}

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response postUser(User user){
userRepo.insert(user);
return Response.ok().status(Status.OK).build();
}

@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response putUser(User user){
userRepo.update(user);
return Response.ok().build();
}

@DELETE
@Path("/{user_id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("user_id") int user_id){
userRepo.deleteUser(user_id);
return Response.ok().build();
}


}

 com.rest.reporitory

UserRepository.Java :- Intended of repository class to perform CRUD operation over user data.


package com.rest.repository;

import java.util.Collection;

import com.rest.factory.UserRepositoryFactory;
import com.rest.model.User;

public class UserRepository {
private UserRepositoryFactory userFactory = UserRepositoryFactory.getInstance();

public User getUser(int id){
return userFactory.getUser(id);
}

public Collection<User> getAllUsers(){
return userFactory.getListOfUsers().values();
}

public User deleteUser(int id){
return userFactory.deleteUser(id);
}

public void insert(User user){
userFactory.getUpdate(user);
}

public void update(User user){
userFactory.getUpdate(user);;
}
}

 com.rest.model

User.java :- this is a pojo/model java class this is used to wrap the User properties either user response or request parameters.


package com.rest.model;

import java.io.Serializable;

public class User implements Serializable{

/**
*
*/
private static final long serialVersionUID = 3228632501659659215L;
private int id;
private String name;
private String address;
public User(){

}

public User(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

}

 com.rest.factory

UserRepositoryFactory.java:- intended of this factory class to provide User data.


package com.rest.factory;

import java.util.HashMap;
import java.util.Map;

import com.rest.model.User;

public class UserRepositoryFactory {

private static Map<Integer, User> users = new HashMap<Integer, User>();

public Map<Integer, User> getListOfUsers() {
User u1 = new User(101, "Ajay Kumar", "New Delhi");
User u2 = new User(102, "Rahul Kumar", "Goa");
User u3 = new User(103, "Santosh Kumar", "Delhi");
users.put(u1.getId(), u1);
users.put(u2.getId(), u2);
users.put(u3.getId(), u3);
return users;
}

public User getUser(Integer id) {
return users.get(id);
}

public User deleteUser(Integer id) {
return users.remove(id);
}

public void getUpdate(User user) {
if (users.containsKey(user.getId())) {
// update user here
users.put(user.getId(), user);
} else {
// add user
users.put(user.getId(), user);
}
}

private UserRepositoryFactory() {
}

private static UserRepositoryFactory userRepository = new UserRepositoryFactory();

public static UserRepositoryFactory getInstance() {
if (userRepository == null) {
synchronized (UserRepositoryFactory.class) {
userRepository = new UserRepositoryFactory();
}
}
return userRepository;
}
}

Web-description file ( web.xml ):-


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>RESTfulExample1</display-name>

<servlet>
<servlet-name>REST</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.jersey.jaxb,com.fasterxml.jackson.jaxrs.json,com.rest.service
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>REST</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

GET method:-

  • /rest/user : – Fetch all users
  • /rest/user/101 – Fetch User which id is 101

GET-User

POST method :-

  • /rest/user :- Add User
    • Method:Post
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Rahul Kumar”, “address”: “Goa” }
    • Return Response : Response Status OK

POST-User

PUT method :-

  • /rest/user :- Update User
    • Method:PUT
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Any name”, “address”: “Any City” }
    • Return Response : Response Status OK

PUT-User

DELETE method :-

  • /rest/user/101 :- Delete User which user id is 101
    • Method:DELETE
    • Return Response : Response Status OK

DELETE-User-BY-ID

Below step’s are done using RESTful tools to fire rest services

 Download Complete source code from here

 

RESTful Service in Java

Posted on Updated on

RESTful Service in Java.

Table of Contents:-

  1. What is RESTful service in Java ?
  2. How to implement it in Web Application ?

 

What is RESTful service in Java ?

Representation state transfer(REST) is architecture style that specifies constraints i.e Uniform resource identifier(URI). REST architecture style represents data,functionality as resources that are accessed by URI. REST create a bridge between Client/Server architecture and communicate over stateless HTTP protocol and Client/Server exchange representation  resources by using standardized interface and protocol.

URL ( Uniform Resource Locator ) formation :-

URL : <Protocol> ://< Hostname> :< port>/<Context-name>/<URL>

http://localhost:8080/RESTfulExample1/rest/user/102

RESTful ( JAX-RS) annotation summary :-

  • @path : – It’s used to represents an URI path template which the resource response it.
  • @consume :- It’s used to specify MIME media type representation of a resource can consume that were sent by client.
  • @produce :- it’s used to specify MIME media type representation of a resource can produce that send back to client like “application/json”,”application/text”.
  • @ParamPath :- The @PathParam annotation is a type of parameter that you can extract for use in your resource class.URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
  • @QueryParam :- The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
  • @Context :- @Context can be used to obtain contextual Java types related to the request or response.

How to convert an Object into Response Type (“JSON/Text/Xml”):-

Using javax.ws.rs.core.Response , contract between a returned instance and the runtime when an application needs to provide metadata to the runtime.

@GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getUsers(){
 return Response.ok().entity(userRepo.getAllUsers()).build();
 }

HTTP methods :-

  • GET : – it’s used to read a specified resource.
  • POST :- it’s used to create a specified resource.
  • PUT :-  it’s used to update a specified resources
  • DELETE :-it’s used to delete a specified resources
  • HEAD :- Same as GET but returns only HTTP headers and no document body

Key Points :-

  • It’s not a protocol.
  • It’s a architecture style that represent a resources that are accessed by URI.
  • Communication over HTTP is stateless.
  • It’s scalable,reliable and portable by nature.

Example with source code below :

  1. RESTful example with Tomcat and Maven.

Importants of hashcode and equals method in Java

Posted on Updated on

Importants of hashcode and equals method in Java

These two is core part of Collection in Java and most frequently asked question in interview. In this article we will discuss all related points.

hashcode and equals methods are two fundamental topics from java.lang.Object class which is used to compare two Object using equality and calculate the memory address of Object using hashcode function.  primarily uses of these two function in Collection in java like HashMap,Hashtable,etc.

Default implementation of these two methods in java.lang.Object class :-

hashcode method :- it’s a native method means implemented directly in ‘native code’ in JVM that return distinct integer value for distinct Objects. Typically it’s converted internal memory address of Object into integer. Ideally a hashcode method represent an Object so distinct Object having distict hashcode values.

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

public native int hashCode();

equals method:- Default implementation is comparing two Object by reference and return true if Objects reference are same otherwise false.

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used inequals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.
public boolean equals(Object obj) {
return (this == obj);
}

 Contract Implementation of these methods and their uses:-

In general, contract of overridden implementation of these methods give us a consistent behaviours of same Object every time.It is not mandatory to implement but recommended to implement these methods when Object to be used in Collection part.

Key Points :-

    • Two objects are equals according to equals() must return same hashcode for each of Object but in opposite two Objects having same hashcode may not be equals by equals().
    • Invalid or unimplemented of these two overridden methods of Object class may cause serious issues in our application.
    • If hashcode() return same hash value for Objects then internally a LinkedList chain would be created against that key and maintains Key/Value Pairs in Entry Object.

Internal implementation of static class Entry.Java in HashMap

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

Internal implementation of put() in HashMap

 
    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

Example :-

import java.util.HashMap;
import java.util.Map;

class Employee {
	private long id;
	private String name;
	private String address;
	public Employee(long id,String name,String address){
		this.id=id;
		this.name = name;
		this.address = address;
	}
        /**
         * Getter/Setter ....
         */ 
 
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result + (int) (id ^ (id >>> 32));
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
}

Here, Three distinct Employee Object is created, each of them has different properties and stored into HashMap. During this discussion we will see what will happen if hashcode() is not implemented.
Main Class here :-


public static void main(String args[]){
Map<Employee,Employee> map = new HashMap<Employee,Employee>();
Employee e1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3 = new Employee(1003, "Wasim Akram","Delhi");

map.put(e1, e1);
map.put(e2, e2);
map.put(e3, e3);
}

case 1 : if hashcode() is not override in Employee class then


map.containsKey(new Employee(1001, "Ajay Kumar","Delhi"));// false
map.containsKey(new Employee(1002, "Santosh Kumar","New Delhi")); // false
map.containsKey(new Employee(1003, "Wasim Akram","Delhi")); // false
map.containsKey(e1) // true
map.containsKey(e2) // true
map.containsKey(e3) // true

case 2 : if hashcode() is override in Employee class then


map.containsKey(new Employee(1001, "Ajay Kumar","Delhi"));// true
map.containsKey(new Employee(1002, "Santosh Kumar","New Delhi")); // true
map.containsKey(new Employee(1003, "Wasim Akram","Delhi")); // true
map.containsKey(e1) // true
map.containsKey(e2) // true
map.containsKey(e3) // true

case 3 : if equals() is not override in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");
		
System.out.println(e1.equals(e1_1)); // false
System.out.println(e2.equals(e2_2)); // false
System.out.println(e3.equals(e3_3)); // false

case 4 : if equals() is override in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");
		
System.out.println(e1.equals(e1_1)); // true
System.out.println(e2.equals(e2_2)); // true
System.out.println(e3.equals(e3_3)); // true

case 5 : if hashcode() is override but equals() is not in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(e1.equals(e1_1)); // false
System.out.println(e2.equals(e2_2)); // false
System.out.println(e3.equals(e3_3)); // false

case 6 : if hashcode() returns fixed value but equals() is not override in Employee class then

@Override
 public int hashCode() {
 return 31;
}
Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(map.get(e3_3)); // null
System.out.println(map.get(e3)); // Employee [id=1003, name=Wasim Akram, address=Delhi]

case 7 : if hashcode() returns fixed value and equals() is override in Employee class then

@Override

//Employee.Java 
public int hashCode() {
 return 31;
}
@Override
public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
}

//Main.Java Class	
Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(map.get(e3_3)); // // Employee [id=1003, name=Wasim Akram, address=Delhi]

System.out.println(map.get(e3)); // Employee [id=1003, name=Wasim Akram, address=Delhi]

 

Interview Question :-

What is hashcode and equals methods ?
hashcode() is a native method of java.lang.Object class this is a technique to calculate the memory address of object into integer value. Ideally, hashcode assign each Object as key to unique bucket in Map.

equals method is used to compare between two Objects and it return true if Objects are equals according to their implementation otherwise return false. It is used to search an Object into bucket of Map implementation.

Why it’s important to override these methods.

As we discussed below, each object has their hashcode which represent Object identity. Also it guarantee then same hash value will be generated consistently every time for same Object by override this method.so it’s important to implemented in our Bean class. Whenever we use this object as Key in Map implementation then a bucket is assigned to Entry<Key,Value> object by calculated hash code of key Object otherwise default implementation of native hashcode() from java.lang.Object Class will be applied which produce inconsistent behaviours in Java compiler.

In the same way, default implementation of equals() methods return false every time for every mutable Object by equality, just because it’s compare objects reference by default not by Object content.

What is hashing technique ?

It’s a technique to compute hash value of Object, Once the hash value is computed then we can insert into hashtable at designated position or bucket. In Java using hashcode() map each Object into unique slot.

What happened if hashcode() is not overridden ?

If we don’t implement hashcode method then default implementation of Object class is used to store and retrieve Object value from Hashtable,HashMap and HashSet, subsequently result would be incorrect. Hence it’s recommended to override these two method.

Two Objects which are equals according to equals() then what their hash value ?

if two Objects are equals according to equals() then hashcode() produce same hash value.

What is hash Collision?

Often it’s not possible if implemented hashcode() is perfect but when two objects hash point to same slot or bucket then it will happen therefore internally a linked list chain will be created that store the Entry Object.

Difference between ‘==’ and equals() method.

‘==’ is a Java operator which is used to compare two operands reference or values.
equals() is a method from java.lang.Object class with check object content.

Difference between equals() and compareTo() ?

  • equals() methods came from java.lang.Object class while compareTo() came from java.lang.comparable interface.
  • equals() return false if it’s compare with Null reference while compareTo return NullPointerException.
System.out.println(e1.equals(null)); // false
System.out.println("Say Hello".compareTo(null)); // Exception in thread "main" //java.lang.NullPointerException
//at java.lang.String.compareTo(Unknown Source)
  • compareTo() only work on those Object that implements Comparable interface.
  • equals() method returns boolean value while compareTo() return integer value.

 

 

What is transient variable in Java

Posted on Updated on

What is transient variable in Java

transient is a keyword in Java, which means variable is marked transient to indicate that they are not part of persistent state while Object is being saved into File system or DB.

Today we are moving toward annotation base programming rather than manual configuration and sometime we declared properties in Pojo class in which we marked few of perperties as transient then that properties only useful at application level not DB or File System.Hence we can control fields being saved during Serialization process using transient keywork.

Below example of Weather.Java indicate that temperature field value is not saved into File System or dB. Only city field value would be saved.


public class Weather {
private String city;
private transient String temperature;
--------
--------
}

Similarly, if you are familiar with MondoDB or Hibernate Annotation base Pojo class, Same way we can control the fields from being persistence state.

LoginModel.Java :- Mongodb pojo Java Class

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "Login")
public class LoginModel {
 
 @Id
 private String id;
 private String userName;
 private String password;
@Transient
private String sessionId;
-------------
-------------
 Below are complete code of transient-

Weather.Java is a Serialized Java class.

import java.io.Serializable;

public class Weather implements Serializable {
 /**
 * 
 */
 private static final long serialVersionUID = 2983365916512327738L;
 private String city;
 private transient String temperature;

 public Weather(String city, String temperature) {
 this.city = city;
 this.temperature = temperature;
 }

 public String getCity() {
 return city;
 }

 public void setCity(String city) {
 this.city = city;
 }

 public String getTemperature() {
 return temperature;
 }

 public void setTemperature(String temperature) {
 this.temperature = temperature;
 }

 @Override
 public String toString() {
 StringBuilder builder = new StringBuilder();
 builder.append("Weather [city=").append(city).append(", temperature=")
 .append(temperature).append("]");
 return builder.toString();
 }

}

 WeatherSerializationService .java : read or write Object as serialization form


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;


public class WeatherSerializationService {
	
	private static final String FILE_NAME="weather.sar";
	
	public static void main(String args[]){
		Weather weather = new Weather("Delhi","42'C");
		WeatherSerializationService weatherService = new WeatherSerializationService();
		System.out.println("Save Serializated Object "+weather);
		weatherService.save(weather);
		
		Weather readWeather = weatherService.retrive();
                if( null == readWeather ){
                    System.out.println(" Unable to read Serialization Object - Weather ");
                }
		System.out.println("Read Serializated Object "+readWeather);
		
	}
	public void save(Weather weather){
		FileOutputStream fileOutputStream = null;
		ObjectOutput objectOut = null;
		try {
			fileOutputStream = new FileOutputStream(FILE_NAME);
			objectOut = new ObjectOutputStream(fileOutputStream);
			objectOut.writeObject(weather);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null == objectOut ) return;
                                if(null == fileOutputStream ) return;
				objectOut.close();
				fileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	public Weather retrive(){
		ObjectInput objectInput = null;
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(FILE_NAME);
			objectInput = new ObjectInputStream(inputStream);
			return (Weather)objectInput.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null == objectInput ) return null;
				if(null == inputStream ) return null;
				
				objectInput.close();
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}

Output here :-

Save Serializated Object Weather [city=Delhi, temperature=42’C]
Read Serializated Object Weather [city=Delhi, temperature=null]

 

What is Serialization in Java

Posted on Updated on

What is Serialization in Java

Java provides a mechanism  to convert Object into bit of Stream which includes Object data and information also Type and it’s values. Java provide automatic Serialization which required class must be implementing java.io.serialization interface.

Process of serialization is also called marshalling and in opposite reconstructing a serialization Object by extracting all fields from byte code is called as De-Serialization or unmarshalling.

Serialization is an interface that belong to java.io package which is also called as Marker class.

Marker Class :- A class that has no method and fields within it is called Marker Class. Java provides few marker class as below :

Searilizable,Cloneable,Remote,ThreadSafe interface

Where it is used :-

  • To transmit object over/across Network.
  • To buffer or in memory File system store.
  • RMI call in distributed environment.
  • Component base programming like CORBA,COM

read here about Why SerialVerisonUID is important

Key Points :-

  • transient/static type can not be serialized.
  • To extract or deserialization from series of bytes into Object may be claused in different JVM compiler if serialVersionUID is not implemented.
  • Serialization/Deserialization is a recursive process which may be cause performance footprint.

 

Example :-

  1. How to Serializated multple Object

 

How to Serialized multiple Object in Java

Posted on Updated on

 

HostPersistor.Java


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.bean.HostInfo;

public class HostPersistor {

    static Map HostInfoMap = new Hashtable();
    public static void write(HostInfo obj) {

        FileOutputStream fout = null;
        ObjectOutputStream objout = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            if (!file.exists()) {
                file.createNewFile();
            }
            fout = new FileOutputStream(file);

            if (!HostInfoMap.containsKey(obj)) {
                HostInfoMap.put(obj.getIpaddress(),obj);
                objout = new ObjectOutputStream(fout);
                for (Map.Entry info : HostInfoMap.entrySet()) {
                    objout.writeObject(info.getValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (objout != null)
                    objout.close();
                if (fout != null)
                    fout.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    
    private static Set readObject() {

        FileInputStream fin = null;
        ObjectInputStream objin = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            objin = new ObjectInputStream(new FileInputStream(file));
            while (true) {
                try {
                    HostInfo info = (HostInfo) objin.readObject();
                    HostInfoMap.put(info.getIpaddress(),info);
                } catch (Exception e) {
                    break;
                }

            }
        } catch (IOException e) {

        } finally {
            try {
                if (objin != null)
                    objin.close();
                if (fin != null)
                    fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return HostInfoMap.keySet();
    }

    public static Set getHostInfos() {
        return readObject();
    }

    public static List getHosts(){
        
        List list = new ArrayList();
        list.addAll(getHostInfos());
        Collections.sort(list);
        return list;
        
    }
    

    public static void main(String args[]) throws IOException {

        
        HostInfo info1 = new HostInfo("xxxx", "xx", "xxx", 22);
        HostInfo info2 = new HostInfo("aaaa", "aaaa", "aaa", 22);
        HostInfo info3 = new HostInfo("yyyyy", "yyy", "yyyy", 22);
        
        write(info1);
        write(info2);
        write(info3);
        
        for(String info : getHostInfos()){
            
            System.out.println(info);
            
        }
        
        
        //System.out.println(getHosts());
    }


    public static Map getHostInfoMap() {
        return HostInfoMap;
    }


    public static void setHostInfoMap(Map hostInfoMap) {
        HostInfoMap = hostInfoMap;
    }

}

HostInfo.Java bean which describe host information.


import java.io.Serializable;
import java.util.Stack;

/**
 * @author ajaykumar.gupta
 *
 */

public final class HostInfo implements Serializable,Comparable {

    private static final long serialVersionUID = 6243919138889562890L;

    private String ipaddress;
    private String username;
    private String password;
    private String pwd;
    private Stack cmdList = new Stack();

    private int port;
    

    public HostInfo(String ipaddress, String username, String password, int port) {

        this.ipaddress = ipaddress;
        this.username = username;
        this.password = password;
        this.port = port;
        
        cmdList.add(this.username+"@"+this.ipaddress);

    }

    public String getIpaddress() {
        return ipaddress;
    }

    public void setIpaddress(String ipaddress) {
        this.ipaddress = ipaddress;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Stack getCmdList() {
        return cmdList;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("HostInfo [ipaddress=");
        builder.append(ipaddress);
        builder.append(", username=");
        builder.append(username);
        builder.append(", password=");
        builder.append(password);
        builder.append(", port=");
        builder.append(port);
        builder.append(", pwd=");
        builder.append(pwd);
        builder.append(", cmdList=");
        builder.append(cmdList);
        builder.append("]");
        return builder.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((ipaddress == null) ? 0 : ipaddress.hashCode());
        result = prime * result + port;
        result = prime * result
                + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        HostInfo other = (HostInfo) obj;
        if (ipaddress == null) {
            if (other.ipaddress != null)
                return false;
        } else if (!ipaddress.equals(other.ipaddress))
            return false;
        if (port != other.port)
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

    @Override
    public int compareTo(HostInfo o) {
        return this.ipaddress.compareTo(o.ipaddress);
    }
    
    
    

}