Month: July 2015

How to create an Immutable Object using Builder Design Pattern

Posted on Updated on

java-logo

In my last post “What is Immutable Object in java“, We discuss what is Immutable Object and their advantage. In this post we will discuss, how to create a Immutable Object using Builder design pattern when constructing an Object depends on large number of arguments is more confusion in their order. Also another helpful aspect of using Immutable Builder class is with testing features.

The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.

The builder design pattern provides a way for you to build complex immutable objects. The process is:

  1. The client calls a constructor (or static factory) with all the required parameters and gets a builder object.
  2. The client calls setter like methods to set each optional parameter of interest.
  3. Finally the client calls the build method to generate the object which is immutable.

Implementation of UserProfile Immutable Class



/**
 * 
 * @author #Ajay
 *
 */
public final class UserProfile {
	private final String firstName;
	private final String middleName;
	private final String lastName;

	private final String email;
	private final String resumePath;
	private final String contentType;

	private final String imagePath;
	private final String imageContentType;

	private final String coverPath;
	private final String contentTypeCover;

	private final String jobTitle;

	private final String phone1;
	private final String phone2;
	private final String phone3;

	private UserProfile(UserProfileBuilder user) {
		this.firstName = user.firstName;
		this.middleName = user.middleName;
		this.lastName = user.lastName;
		this.email = user.email;
		this.resumePath = user.resumePath;
		this.contentType = user.contentType;
		this.imagePath = user.imagePath;
		this.imageContentType = user.imageContentType;
		this.coverPath = user.coverPath;
		this.contentTypeCover = user.contentTypeCover;
		this.jobTitle = user.jobTitle;
		this.phone1 = user.phone1;
		this.phone2 = user.phone2;
		this.phone3 = user.phone3;
	}

	/*
	 * UserProfileBuilder class
	 */
	public static class UserProfileBuilder {
		private String firstName;
		private String middleName;
		private String lastName;

		private String email;
		private String resumePath;
		private String contentType;

		private String imagePath;
		private String imageContentType;

		private String coverPath;
		private String contentTypeCover;

		private String jobTitle;

		private String phone1;
		private String phone2;
		private String phone3;

		/*
		 * Optional methods
		 */
		public UserProfileBuilder FirstName(String firstName) {
			this.firstName = firstName;
			return this;
		}

		public UserProfileBuilder MiddleName(String middleName) {
			this.middleName = middleName;
			return this;
		}

		public UserProfileBuilder LastName(String lastName) {
			this.lastName = lastName;
			return this;
		}

		public UserProfileBuilder Email(String email) {
			this.email = email;
			return this;
		}

		public UserProfileBuilder ResumePath(String path) {
			this.resumePath = path;
			return this;
		}

		public UserProfileBuilder ContentType(String contentType) {
			this.contentType = contentType;
			return this;
		}

		public UserProfileBuilder ImagePath(String imagePath) {
			this.imagePath = imagePath;
			return this;
		}

		public UserProfileBuilder ImageContentType(String imageContentType) {
			this.imageContentType = imageContentType;
			return this;
		}

		public UserProfileBuilder CoverPath(String coverPath) {
			this.coverPath = coverPath;
			return this;
		}

		public UserProfileBuilder ContentTypeCover(String contentTypeCover) {
			this.contentTypeCover = contentTypeCover;
			return this;
		}

		public UserProfileBuilder JobTitle(String title) {
			this.jobTitle = title;
			return this;
		}

		public UserProfileBuilder Phone1(String phone1) {
			this.phone1 = phone1;
			return this;
		}

		public UserProfileBuilder Phone2(String phone2) {
			this.phone2 = phone2;
			return this;
		}

		public UserProfileBuilder Phone3(String phone3) {
			this.phone3 = phone3;
			return this;
		}

		/*
		 * Build UserProfile Object
		 */
		public UserProfile build() {
			return new UserProfile(this);
		}

	}

	public static void main(String args[]) {
		/*
		 *  Construct an Immutable Object of UserProfile using Builder Design Pattern.
		 */
		UserProfile userProfile = new UserProfile.UserProfileBuilder()
				.FirstName("Santosh")
				.MiddleName("Kumar")
				.LastName("Yadav")
				.Phone1("234234")
				.Email("abc@gmail.com")
				.build();
	}
}

In this way you build a complex object which is immutable and has all the advantages of immutable objects.

Application Server vs Web Server ?

Posted on Updated on

java-logo

Both Web Server and Application Server are used to deploy J2EE or other web application, base on Business requirement it’s preferred to chose either of them. In most of case web application is used for small application where only Servlet Container and Connection pool are required like Tomcat,Jetty. But as Application become enterprise and run on distribute operating system and required these modules like Connection pooling, Transaction management, messaging, clustering,session-failover, load balancing and persistence then we move to Application Server like JBoss, Bea,WebLogic, Websphere server, etc.

An Application server is a component-based product that resides in the middle-tier of a server centric architecture. It provides middleware services for security and state maintenance, along with data access and persistence.

Following are key feature of Application and Web Server :-

  1. Web Server is designed to serve HTTP Content. Application Server can also serve HTTP Content but is not limited to just HTTP. It can be provided other protocol support such as RMI/RPC .
  2. Web Server is mostly designed to serve static content, though most Web Servers have plugins to support scripting languages like Perl, PHP, ASP, JSP etc. through which these servers can generate dynamic HTTP content.
  3. Web Server is a sub-set of Application Server means most of Application can also contain Web Server as internal part of them.
  4. Web Server only supports HTTP protocol but Application Server not only supports HTTP protocal but also other protocol like RMI,TCP/IP and other.
  5. Web Server is light process and it consume less memory but Application Server is a heavy process and consume more memory than web server.
  6. Web application does not support EJB (.ear) but supports in Application Server.

 

Web Server

  • IIS : ASP (.NET)
  • Tomcat : Servlet
  • Jetty : Servlet
  • Apache : Php, CGI

Application Servers

  • MTS : COM+
  • WAS : EJB
  • JBoss : EJB
  • WebLogic Application Server : EJB

When We use an Application Server :-

You should consider an application server when you have a need for:

  • Integration with existing systems and databases
  • Website support
  • Load balancing and Session fail-over

Secondary reasons to use application servers derive from the primary reasons. A few secondary reasons are:

  • E-Commerce
  • Web-integrated collaboration
  • Component re-use

What is Immutable Object in Java

Posted on Updated on

java-logo  It is mostly asked interview question, Interview may asked you ” what is Immutable object ” or ” write a custom immutable class in java” and “benefit over mutable Object” that  We will discuss in later.

An Object whose reference never change after construction is called Immutable Object. If any changes made on Immutable Object then it’s created and referred to another reference. for example:- String class and all wrapper class are immutable by nature.

How to create an Immutable Class in Java.

  • Make all fields “private” and “final”.
  • Don’t provides Setter method – methods that changes fields value or reference.
  • Declare class as final so all instance methods are not allowed to override.
  •  If the instance fields include references to mutable objects, don’t allow those objects to be changed:-Don’t provide methods that modify the mutable objects.
    • Don’t provide methods that modify the mutable objects.
    •  Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies or clone that object, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

Benefit of Immutable Object in Java :-

  1. It’s thread-safe means it’s guarantees that object state will be safe in multi-threading environment without using synchronized keyword.
  2. Immutable object are good to use as a Key in Map or Set. Since typically  Key object reference do not change once it’s created.
  3. Immutability makes it easier to parallelize your program as there are no conflicts among objects,
  4. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).
  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.

As a good programming practice in Java 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. When you care a lot about performance (e.g. programming a game) it may be necessary to use a mutable object. Even then it is often better to try to limit the mutability of objects. This recommendation can be summarized in the following adage by Joshua Bloch (taken from the book Effective Java) –

“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.”

How to create an Immutable Object in Java:-


/**
 * 
 * @author #Ajay
 *
 */

public final class Employee {
	
	/**
	 *  All fields are private final
	 */
	private final String name;
	private final String age;
	private final String address;

	/*
	 *  Construct an Object here using constructor
	 */
	public Employee(String name,String age, String address){
		this.name = name;
		this.age = age;
		this.address = address;
	}

	/*
	 *  Only getter methods are allowed
	 */
	public final String getName() {
		return name;
	}

	public final String getAge() {
		return age;
	}

	public final String getAddress() {
		return address;
	}
	
	
}

Immutable example which include mutable object


import java.util.Date;

/**
 * 
 * @author #Ajay
 *
 */

public final class Employee {

	/**
	 * All fields are private final
	 */
	private final String name;
	private final String age;
	private final String address;

	/*
	 * Immutable object include mutable reference type i.e Date
	 */
	private final Date dateOfJoining;

	/*
	 * Construct an Object here using constructor
	 */
	public Employee(String name, String age, String address, Date doj) {
		this.name = name;
		this.age = age;
		this.address = address;
		this.dateOfJoining = new Date(doj.getTime());
	}

	/*
	 * Only getter methods are allowed
	 */
	public final String getName() {
		return name;
	}

	public final String getAge() {
		return age;
	}

	public final String getAddress() {
		return address;
	}

	/*
	 * Preserve Object reference changed so we create a clone of Object.
	 */
	public final Date getDateOfJoining() {
		return (Date) dateOfJoining.clone();
	}

}

 

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space

Posted on Updated on

java-logo Every Java programmer faced such Error “java.lang.OutOfMemoryError” during course of program.

It’s considered as Error in Java which occurs when Heap ran out of memory or do not have enough memory to execute the program, in such circumstance JVM throw error i.e OutOfMemoryError.

On the safe side, your application need more memory to execute or some kind of memory leakage occurred in your code.

 

Solution :- 

  • Increase Heap size by sitting VM argument
    • -Xms <size>: specifies the minimum Java heap size i.e -xms512m
    • -Xmx <size>: specifies the maximum Java heap size i.e  -xms1024m
  • If you are facing such issue in your IDE like eclipse then
    • Right click on your program in project
    •  Select run as -> run configuation…
    • select argument tab
    • and specify min and max Heap size in VM argument i.e -Xmx512m -Xmx1024m

 

see more

java.lang.OutOfMemoryError: Requested array size exceeds VM limit

Posted on Updated on

java-logo

Java has got a limit on maximum Array size allocation i.e -231 to 231-1 . The exact limit is platform specific.

when your application get crashed and throw java.lang.OutOfMemoryError: Requested array size exceeds VM limit  that means trying to allocate an array which size is larger than VM supports size.

Example here :-

int [] arr = new int[Integer.MAX_VALUE];
or
int [] arr = new int[Integer.MAX_VALUE-1];
output :-

Exception in thread “main” java.lang.OutOfMemoryError: Requested array size exceeds VM limit

Solution :

The java.lang.OutOfMemoryError: Requested array size exceeds VM limit can appear as a result of either of the following situations:

  • Your arrays grow too big and end up having a size between the platform limit and the Integer.MAX_INT
  • You deliberately try to allocate arrays larger than 2^31-1 elements to experiment with the limits.

Initializes array size with Integer.MAX_VALUE-2 to get rid of such errors  : –

int [] arr = new int[Integer.MAX_VALUE-2];

 

see more

Thanks

 

 

 

What is String pool in Java

Posted on Updated on

String pool is an special area of Method Area in JMM( Java Memory Model ) that store String literals and return same reference which contain are already exists in the Pool. Only one Method Area exists per JVM ( Java Virtual Machine ) that is shared among all JVM Threads Object. Method Area is created at time on JVM start-up, Although the method area is logically part of the heap.

A run-time Constants pool is  created per-class or per-interface at runtime representation of constant_table in per class file. Each runtime constant-pool is allocated in Java virtual machine’s Method Area. A runtime constant-pool is created per-class or per-interface at run-time when class or interface is constructed by JVM.

As you know String is a immutable class means every change made on String create a new ( Object ) memory location in Heap.

java-string-pool

When we create a String literals then it first check the contains of String into String Pool if it already exists in the pool then reference of existing String literals will be returned otherwise it put into String pool instead of creating a new String Object.

Following example create only one Object :-

String string1 = "abcd";
String string2 = "abcd";

First String literals “abcd” will be looked up into String Pool if it’s not exist then it will be created an Object in Heap but again second line get executed it first check into String Pool and found String literals “abcd” in pool so rather then creating a new Object of String it returns the existing String reference.

Following are example that will give more idea about String Pool:-

both s1 and s2 String variable point to same reference just because it is internally store into String pool. Although == operator and equals() returns same value i.e true.

String s1 = “jim”;
String s2 = “jim”;

System.out.println(s1==s2); // true.
Object s2 is the same object with s1. But if you create using new operator:
String s1 = “jim”;
String s2 = new String(“jim”);
System.out.println(s1==s2); //false.
It will allocate new Object instead getting from String constant pool.
Another sample:
String s1 = “jim”;
String s2 = “j”+”im”;String s3 = “j”;
String im = “im”;
s3+= im;
System.out.println(s1==s2); //true.System.out.println(s1==s3); //false.
Concatenation during runtime will create new String Object.
Sample if using final modifier:
final String s1 = “j”;
final String s2 = “im”;
String jim = “jim”;
System.out.println(s1+s2 == jim); // returns true: Constant expression.
String s3 = “j”;
String s4 = “im”;
System.out.println(s3 + s4 == jim); // returns false: Not a constant expression.

 

Another important point to keep in mind that intern() in String class which make sure once String get interned then string constant will be added in String pool.

Example here :-

String s1 = "test";
String s2 = new String("test");  // "new String" guarantees a different object

System.out.println(s1 == s2);  // should print "false"

s2 = s2.intern();
System.out.println(s1 == s2);  // should print "true"