Month: March 2016

What is a StackOverflowError?

Posted on Updated on

Before going to next parameters, I would like to tell you how the local variable are stored in stack

enter image description here

if you see in the image you will be able to understand how things are working.

When a function call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM). The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided. An example that throws a StackOverflowError is shown below:

StackOverflowErrorExample.java:

public class StackOverflowErrorExample {

    public static void recursivePrint(int num) {
        System.out.println("Number: " + num);

        if(num == 0)
            return;
        else
            recursivePrint(++num);
    }

    public static void main(String[] args) {
        StackOverflowErrorExample.recursivePrint(1);
    }
}

In this example, we define a recursive method, called recursivePrint that prints an integer and then, calls itself, with the next successive integer as an argument. The recursion ends once we invoke the method, passing 0 as a parameter. However, in our example, we start printing numbers from 1 and thus, the recursion will never terminate. A sample execution, using the -Xss1M flag that specifies the size of the thread stack to equal to 1MB, is shown below:

Number: 1
Number: 2
Number: 3
...
Number: 6262
Number: 6263
Number: 6264
Number: 6265
Number: 6266
Exception in thread "main" java.lang.StackOverflowError
        at java.io.PrintStream.write(PrintStream.java:480)
        at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
        at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
        at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
        at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
        at java.io.PrintStream.write(PrintStream.java:527)
        at java.io.PrintStream.print(PrintStream.java:669)
        at java.io.PrintStream.println(PrintStream.java:806)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:4)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        ...

Depending on the JVM’s initial configuration, the results may differ, but eventually the StackOverflowError shall be thrown. This example is a very good example of how recursion can cause problems, if not implemented with caution.

How to deal with the StackOverflowError

  1. The simplest solution is to carefully inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code being recursively called. Once you detect these lines, you must carefully inspect your code and understand why the recursion never terminates.
  2. If you have verified that the recursion is implemented correctly, you can increase the stack’s size, in order to allow a larger number of invocations. Depending on the Java Virtual Machine (JVM) installed, the default thread stack size may equal to either 512KB, or 1MB. You can increase the thread stack size using the -Xss flag. This flag can be specified either via the project’s configuration, or via the command line. The format of the -Xss argument is: -Xss[g|G|m|M|k|K]

How to determine, how many objects are created for an Object in Java

Posted on

6db3a-downloadThis is a very tricky question that may be asked in Java/J2EE interview, most of the candidate get confused to give the answer at right minor and start thinking over and over again but when you finally realized  in cool mind then the answer would be at around you.

Most of Java/J2EE developer has enough knowledge of static keyword in Java and their behavior to implementation. Just think again and try to fix the puzzle question, Well now it not more harder to guess the answer.

Of course, yes.. Using the static, we can figure out the how many objects are created during the life cycle. below are some snippet code through it can be determined.

In the below,  we want to figure out the nos of Employee object are created during the life cycle of the application so we introduce a class variable i.e objectCounter in Employee Class which increment by one every time in the constructor so whenever Employee instance will be created, subsequently counter get increment by one.

CountNumberOfObjectsCreated.Java



public class CountNumberOfObjectsCreated {

	public static void main(String args[]) {
		Employee e = null;
		for (int i = 0; i <= 10; i++) {
			e = new Employee();
		}
		System.out.println("Number of Employee Object is ::" + Employee.objectCounter); // 11 Objects are created here.
	}

}

class Employee {
	public static long objectCounter = 0;
	private Long id;
	private String name;
	private String email;

	public Employee() {
		objectCounter++;
	}

	public Employee(Long id, String name, String email) {
		objectCounter++;
		this.id = id;
		this.name = name;
		this.email = email;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}


Although there may be some other way to do this work.  It would be appreciated if someone suggest us to do this work differently.

Thanks
Ajay Kumar

How to implements Read-only Collection and Map in JAVA ?

Posted on Updated on

6db3a-download A read-only Collection Or Map means not any modification operation will be performed over the Collection or Map like get(),put(),addAll(),remove() etc.  JAVA provides some built-in factory methods that make a Collection or Map structure read-only thereafter no any modification will be performed, Also we can implement own Read-only Collection or Map that will be discussed in this post.  If any modification will be held on read-only collection then an exception will be thrown i.e java.lang.UnSupportedOperationException.

 

Java Built-in Factory Methods of Collections Helper Class

  • Collection unmodifiableCollection(Collection collection)
  • List unmodifiableList(List list)
  • Map unmodifiableMap(Map map)
  • Set unmodifiableSet(Set set)
  • SortedMap unmodifiableSortedMap(SortedMap map)
  • SortedSet unmodifiableSortedSet(SortedSet set)

Another way, We can create customized read-only Collection’s

In below snippet example, instance field List i’e listOfState is a read-only or unmodified list – To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int) and size() methods.

 


private final String states[] = {"A","B","C","D"};
private List listOfState = new AbstractList() {

		@Override
		public String get(int index) {
			return states[index];
		}

		@Override
		public int size() {
			return states.length;
		}
	};


Example of custom read-only list here:-


import java.util.AbstractList;

public class BookList extends AbstractList {

	private final String[] books = { "Java", "jQuery", "javascript", "Restful", "Spring", "Hibernate" };

	public static void main(String[] args) {
		BookList books = new BookList();

		System.out.println(" Print Size of Book List  " + books.size());

		System.out.println(" Print 1st index Book " + books.get(0));
		System.out.println(" Print 2st index Book " + books.get(1));

	}

	@Override
	public String get(int index) {
		return books[index];
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return books.length;
	}

}

Generated Output:-

Print Size of Book List 6
Print 1st index Book Java
Print 2st index Book jQuery

If you try to call remove(), add() or any methods that are used to modify the structure of Collection’s list then it reported an exception i.e java.lang.UnsupportedOperationException

Example of Custom read-only Map here:-  In below implemented class that extends from AbstractMap and disabled  functionalitiy of all those methods through a Map structure could be modified.


import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CityStateMap<K, V> extends AbstractMap<K, V> {

	private final Map<String, String> cityStatesMap = new HashMap<String, String>();

	public CityStateMap() {
		/**
		 * here, we initialized Map's object by feeding some initial values just
		 * for testing.
		 */
		cityStatesMap.put("Delhi", "New Delhi");
		cityStatesMap.put("UP", "Noida");
		cityStatesMap.put("Haryana", "Gurgaon");

	}

	public static void main(String[] args) {

		CityStateMap<String, String> cityStateMap = new CityStateMap<String, String>();
		System.out.println("Cities In UP : " + cityStateMap.get("UP")); // Noida
		System.out.println("Cities In Delhi : " + cityStateMap.get("Delhi")); // New
																				// Delhi
		System.out.println("Cities In Haryana : " + cityStateMap.get("Haryana")); // Gurgaon

		// cityStateMap.remove("UP"); // throw an exception i.e
		// UnsupportedOperationException

	}

	@Override
	public Set entrySet() {
		return cityStatesMap.entrySet();
	}

	@Override
	public V remove(Object key) {
		throw new UnsupportedOperationException();
	}

	public V put(K key, V value) {
		throw new UnsupportedOperationException();
	}

	public void putAll(Map<? extends K, ? extends V> m) {
		throw new UnsupportedOperationException();
	}

	public void clear() {
		throw new UnsupportedOperationException();
	}

}


 

Thanks
Ajay Kumar
————–

Embedded Collections in Hibernate 4.x with Example

Posted on Updated on

Hibernate

In previous post we have seen the mapping with embedded object in Hibernate, As we you know  that Embedded object is a Value Object which does not have own associate table, it’s a containing object that embedded into ower tables, Like in previous post  – Address is an Embedded Object which is nither have own table nor mapped in configuration file (hibernate.cfg.xml). I think, it’s enough here.

 

Come to next points, Mapping with Index Collection i.e ArrayList,LinkedList and Array etc. why this is index collection because these collections object has have an Index to store to a Object. Not other collections like Map and Set – these are not index base collections.

Next, In this chapter we will see how to create a One – to – Many relationship with Embedded Collections.

Before going to example section, have a look at below Annotations class which are used in the example-

@ElementCollection:-  Specifies a collection of instances of a basic type or embeddable class.

@ElementCollection(fetch=FetchType.EAGER)

An @ElementCollection can be used to define a collection of Embeddable objects which stored in seperate Collection Tables not in source Object’s table. This is similar to a OneToMany, except the target object is an Embeddable instead of anEntity. This allows collections of simple objects to be easily defined, without requiring the simple objects to define an Id or ManyToOne inverse mapping. @ElementCollection can also override the mappings, or table for their collection, so you can have multiple entities reference the same Embeddable class, but have each store their dependent objects in a separate table.

Note: The limitations of using an @ElementCollection instead of a OneToMany is that the target objects cannot be queried, persisted, merged independently of their parent object. They are strictly privately-owned (dependent) objects, the same as an Embedded mapping. There is no cascade option on an ElementCollection, the target objects are always persisted, merged, removed with their parent. ElementCollection still can use a fetch type and defaults to LAZY the same as other collection mappings.

@CollectionId :- Describe an identifier column for a Collections as well as generator() mix strategy and generator.

@CollectionId(columns = {@Column(name=”SKILL_ID”)},generator=”hilo-gen”,type=@Type(type=”long”))

@JoinTable:- This annotation is used in the mapping of associations. It is specified on the owning side of a many-to-many association, or in a unidirectional one-to-many association.

@JoinTable(name=”EMPLOYEE_SKILLS”,
joinColumns = @JoinColumn(name=”EMPLOYEE_ID”)
)

If the JoinTable annotation is missing, the default values of the annotation elements apply. The name of the join table is assumed to be the table names of the associated primary tables concatenated together (owning side first) using an underscore.

In this example sections, We have a Entity Class Employee which is associated with Collection of embedded Object ( Value Type ), After running Main class, Two Tables will be created – one for Entity Table “Employee” and another for Collection Table “EMPLOYEE_SKILLS" as per @JoinTable name attribute.
Employee.Java : A Entity Class.


package com.itexperts.hibernate.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "employee")
public class Employee {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private long id;
	@Column(name = "NAME")
	private String name;
	@Column(name = "EMAIL")
	private String email;
	@Column(name = "PHONE")
	private String phone;

	@Column(name = "description")
	@Lob
	private String description;

	@Column(name = "JOINING_DATE")
	@Temporal(TemporalType.DATE)
	private Date joiningDate;
	@Column(name = "DATE_OF_BIRTH")
	@Temporal(TemporalType.DATE)
	private Date dateOfBirth;
	
	@ElementCollection(fetch=FetchType.EAGER)
	@JoinTable(name="EMPLOYEE_SKILLS",
		 joinColumns = @JoinColumn(name="EMPLOYEE_ID")
			)
	@GenericGenerator(name="hilo-gen",strategy="hilo")
	@CollectionId(columns = {@Column(name="SKILL_ID")},generator="hilo-gen",type=@Type(type="long"))
	private Collection skills = new ArrayList();
	


	public Employee(){}
	public Employee(String name, String email, String phone) {
		super();
		this.name = name;
		this.email = email;
		this.phone = phone;
	}

	public Employee(String name, String email, String phone, String description, Date joiningDate,
			Date dateOfBirth) {
		super();
		this.name = name;
		this.email = email;
		this.phone = phone;
		this.description = description;
		this.joiningDate = joiningDate;
		this.dateOfBirth = dateOfBirth;
	}
       // Getter & Setter of Properties here
   } 
}

Skills.java : Embedded class


package com.itexperts.hibernate.model;

import javax.persistence.Embeddable;

@Embeddable
public class Skills {
	
	private String name;
	public Skills(){}
	public Skills(String name){
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


Main Class:-


package com.itexperts.embeded.example;

import java.util.Date;

import org.hibernate.Session;

import com.itexperts.hibernate.model.Employee;
import com.itexperts.hibernate.model.Skills;
import com.itexperts.utils.HibernateUtils;

public class MainTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Session session = HibernateUtils.getInstance().openSession();
		org.hibernate.Transaction tx = session.beginTransaction();
		
		
		Employee e0 = new Employee("ajay","ajay@gmail.com","2341234123");
		e0.setDescription("This is about Employe desc");
		e0.setDateOfBirth(new Date());
		e0.setJoiningDate(new Date());

		e0.getSkills().add(new Skills("Java"));
		e0.getSkills().add(new Skills("J2EE"));
		e0.getSkills().add(new Skills("Hibernate"));
		e0.getSkills().add(new Skills("Spring"));
		// Take an another Employee in order to save and make more clear....
		
		Employee e1 = new Employee("Rahul","rahul@gmail.com","666666666666");
		e1.setDescription("This is about 2nd Employe desc");
		e1.setDateOfBirth(new Date());
		e1.setJoiningDate(new Date());

		e1.getSkills().add(new Skills("Java"));
		e1.getSkills().add(new Skills("J2EE"));
		e1.getSkills().add(new Skills("Hibernate"));
		e1.getSkills().add(new Skills("Spring"));
		e1.getSkills().add(new Skills("Javascript"));
		e1.getSkills().add(new Skills("jQuery"));
		e1.getSkills().add(new Skills("AngularJS"));
		e1.getSkills().add(new Skills("Oracle"));
		e1.getSkills().add(new Skills("RESTFul"));
		e1.getSkills().add(new Skills("Big DB"));
		
		session.save(e0);
		session.save(e1);
		
		tx.commit();
		session.close();
		
		
		session = HibernateUtils.getInstance().openSession();
		
		Employee e = (Employee)session.get(Employee.class, 1L);
		
		System.out.printf("Name %s, Email %s,Skills %s", e.getName(),e.getEmail(),e.getSkills());
	}
}

Genarated Tables Relationship:-

index-collection-example1

 

Generated Output :-

Hibernate: alter table EMPLOYEE_SKILLS drop foreign key FK31C5AF3A856ECD8
Hibernate: drop table if exists EMPLOYEE_SKILLS
Hibernate: drop table if exists employee
Hibernate: drop table if exists hibernate_unique_key
Hibernate: create table EMPLOYEE_SKILLS (EMPLOYEE_ID bigint not null, name varchar(255), SKILL_ID bigint not null, primary key (SKILL_ID))
Hibernate: create table employee (id bigint not null auto_increment, DATE_OF_BIRTH date, description longtext, EMAIL varchar(255), JOINING_DATE date, NAME varchar(255), PHONE varchar(255), primary key (id))
Hibernate: alter table EMPLOYEE_SKILLS add index FK31C5AF3A856ECD8 (EMPLOYEE_ID), add constraint FK31C5AF3A856ECD8 foreign key (EMPLOYEE_ID) references employee (id)
Hibernate: create table hibernate_unique_key ( next_hi integer )
Hibernate: insert into hibernate_unique_key values ( 0 )
Hibernate: insert into employee (DATE_OF_BIRTH, description, EMAIL, JOINING_DATE, NAME, PHONE) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into employee (DATE_OF_BIRTH, description, EMAIL, JOINING_DATE, NAME, PHONE) values (?, ?, ?, ?, ?, ?)
Hibernate: select next_hi from hibernate_unique_key for update
Hibernate: update hibernate_unique_key set next_hi = ? where next_hi = ?
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_SKILLS (EMPLOYEE_ID, SKILL_ID, name) values (?, ?, ?)
Hibernate: select employee0_.id as id0_0_, employee0_.DATE_OF_BIRTH as DATE2_0_0_, employee0_.description as descript3_0_0_, employee0_.EMAIL as EMAIL0_0_, employee0_.JOINING_DATE as JOINING5_0_0_, employee0_.NAME as NAME0_0_, employee0_.PHONE as PHONE0_0_, skills1_.EMPLOYEE_ID as EMPLOYEE1_0_2_, skills1_.name as name2_, skills1_.SKILL_ID as SKILL3_2_ from employee employee0_ left outer join EMPLOYEE_SKILLS skills1_ on employee0_.id=skills1_.EMPLOYEE_ID where employee0_.id=?
Name ajay, Email ajay@gmail.com,Skills org.hibernate.collection.internal.PersistentIdentifierBag@66e9a2c4