Tuesday, September 23, 2014

Transaction level Persistence Context and Extended level Persistence Context

JPA specification has defined below types of EntityManagers / Persistence Contexts:
·         Extended and transaction-scoped EntityManagers,
·         container-managed or application-managed EntityManagers.
·         JTA or resource-local EntityManager,
Transaction level Persistence Context and Extended level Persistence Context:
By default the Persistence Context level is Transaction. What that means is Persistence Context 'lives' for the length of transaction.If you have multiple queries using same transaction then same persistence context is used for all of them.
As the name suggests, a transaction-scoped persistence context is tied to the lifecycle of the transaction. It is created by the container during a transaction and will be closed when the transaction completes.
Transaction-scoped entity managers are responsible for creating transaction-scoped persistence contexts automatically when needed. We say only when needed because transactionscoped persistence context creation is lazy.
An entity manager will create a persistence context only when a method is invoked on the entity manager and when there is no persistence context available.
In case of Stateless Session bean we have business method that should end when the business method finishes because in next invocation we don’t have an idea which EJB instance we’ll end in. One method = one transaction; only transactional-scoped EntityManager is allowed for SLSB.
You can control if the EntityManager is extended or transactional during the EntityManager injection:
@PersistenceContext(type=javax.persistence.PersistenceContextType.EXTENDED)
EntityManager em;
By default it’s javax.persistence.PersistenceContextType.TRANSACTION.
The extended scope is available only for Stateful EJBs; it makes perfectly sense as the SFSBs can save the state, so end of one business method doesn’t necessary means the end of the transaction.
The lifecycle of an extended persistence context is tied to the stateful session bean to which it is bound.
Unlike a transaction-scoped entity manager that creates a new persistence context for each transaction, the extended entity manager of a stateful session bean always uses the same persistence context.
The stateful session bean is associated with a single extended persistence context that is created when the bean instance is created and closed when the bean instance is removed. This has implications for both the association and propagation characteristics of the extended persistence context.
JPA provides 'Extended Persistence Context'. This could be thought of as the Persistence Context being 'owned' by the EntityManager rather than the Transaction. In this case the same Persistence Context can be used for multiple transactions.
JPA needs to provide this due to the mechanism it uses to support Optimistic Concurrency Checking for objects without a version property. 

Container-managed vs application-managed

When we inject the EntitiyManager with @PersistenceContext as below , what we do is, we ask Container to inject it. Which means it’s a container managed PersistenceContext.
@PersistenceContext
EntityManager em;
Container creates is using the EntityManagerFactory. Remember in Java SE you create it using EntitiyManagerFactory as below, it is application managed:
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("EmployeeService");
EntityManager em = emf.createEntityManager();
Application-Managed Entity Managers in Java SE
@PersistenceUnit(unitName="EmployeeService")
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();
Application-Managed Entity Managers in Java EE
Every application-managed Persistence Context has the extended scope.

JTA vs resource-local

Container managed entity manager = JTA EntityManager.
Application managed Entity Manager = 1. JTA Entity Manager OR 2. Resource Local.

So if you are using application managed entity manager then you can tell jpa to use either resource local or JTA.
In persistence.xml write :
<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
    <persistence-unit transaction-type="RESOURCE_LOCAL" ... >
</persistence>
Other value is “JTA”, which is default too.
If you use resource local then you will have to use following :
EntityManager.getTransaction(), which will give javax.persistence.EntityTransaction and you have to invoke begin(), rollback(), commit();









Wednesday, September 17, 2014

Difference between Stack vs Heap in Java



Difference between Stack vs Heap in Java
Here are few differences between stack and heap memory in Java:
1) Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable,  they are always created inside heap space in Java.


2) Each Thread in Java has there own stack which can be specified using -Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap. to learn more about JVM options see my post 10 JVM option Java programmer should know.


3) If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space. Read more about how to deal with java.lang.OutOfMemoryError  in my post 2 ways to solve OutOfMemoryError in Java.


4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is lot lesser than size of  heap memory in Java.


5) Variables stored in stacks are only visible to the owner Thread, while objects created in heap are visible to all thread. In other words stack memory is kind of private memory of Java Threads, while heap memory is shared among all threads.


That's all on difference between Stack and Heap memory in Java. As I said, It’s important to understand what is heap and what is stack in Java and which kind of variables goes where, how you can run out of stack and heap memory in Java etc. Let us know if you are familiar with any other difference between stack and heap memory in java.

Monday, September 15, 2014

ant task to get system memory

I was facing the problem when trying to run a build.xml.
It was throwing OutOfMemory error.
I wanted to investigate it further , and for that I wanted to print out the free memory of the machine before an after my build ant targets starts executing.

There is no out of box solution from Ant.

I had to write an ant task as below :

package org.kp.common.anttask;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class GetFreeMemory extends Task {

@Override
public void execute() throws BuildException {
Runtime rt = Runtime.getRuntime();
System.out.println(rt.freeMemory());
}

}
In the build.xml define the task as below :

<taskdef name="getFreeMemory"
classname="org.kp.common.anttask.GetFreeMemory" />


To use it just write 
<getFreeMemory/>


Wednesday, September 10, 2014

Absent Code Attribute In Method That Is Not Native Or Abstract In Class File

Java.Lang.ClassFormatError : Absent Code Attribute In Method That Is Not Native Or Abstract In Class File 


This error came up when I was doing the JPA Hibernate development.

Problem is coming because of javaee.jar
I have something like below in pom.xml in my maven dependency.

<dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>6.0</version> </dependency> </dependencies>

Solution is don't use it like this. Above setting will download the jar but it's size is 3KB. Which has nothing but pointers to the java ee apis.

So I downloaded the JEE6 from oracle. Problem is there is nothing called as JEE 6. It's a specification. Oracle download gives Glassfish 3 server , which is reference implementation of the JEE6 specification. So you will not get the javaee.jar that you want. Glassfish has the 3KB jar as you would get by above maven dependency.

Real solution is to download it manually . 
Java ee jar is here for JEE 6 : http://download.java.net/maven/2/javax/javaee-api/6.0/javaee-api-6.0.jar

Tuesday, September 2, 2014

Java Persistence API

JPA is Java Persistence API used by JEE and J2SE applications to access the RDBMS databases.
This is true only upto JPA 2.1 version.
If you want to access NoSQL databases like MongoDB or Oracle NoSQL database from java application then you will have to go for EclipseLink JPA 2.4 or Hibernate Object Mapping for NoSQL datastores.
Hibernate for nosql and Hibernate for sql that is normal JPA are two different things. You can directly use APIs provided by the nosql database vendor like MongoDB. The main advantage of using the EclipseLinkJPA 2.4 is your application will be configuration as opposed to when using directly using nosql database APIs.


Saturday, August 30, 2014

How To Become A Software Architect

So you want to become a Software Architect ? If yes then please read on.

There are 3 types of architects in Software Industry.
1. Application Architect
2. Solutions Architect
3. Enterprise Architect.

If you are a developer currently then you may like to become a team leader first. Once you become a team leader you may aim to become an Application Architect. The application architect a good and experienced team leader. Plus Application Architect would need lot of knowledge about creating High Level Design and Low Level Design documents. Application Architect will have to use the single type of technology. So for example Java Web Application Architect can create MVC type of application.

The Solutions Architect are those who provide solutions to the business as well as team leaders and application architects. 

The Enterprise Architect can provide solutions to the business and they can give recommendations to even switch the platforms. So an enterprise architect can tell the business to switch between java and .net. Application architect cannot do that. Solution architect can do it but his focus would more on solution.

There are different certifications for each type of roles, for application architect there what matters are multiple technical certifications. For Solution architect position you need be more of a business person who is tech savvy, rather than technical person who is business savvy. Enterprise architect is mostly an experienced solution or application architect.

Context Engine

My understanding about Context Engine is :

In simple words "Context Engine" is software program which uses information and internet history of a person to give him recommendations about what he should do now.

Which means if I go to a mall for shopping and there is a movie playing in the theater "how to train your dragon 2", the "Context Engine" software will give me recommendation to watch it if I searched for it last week. 

So basically Context Engine client software installed on my mobile device will have to have access to my web history and also to my present location and things going around at that location.

The Context Engine is a Recommendation Software that can reside on your mobile device.
At the same time if you are a Web application architect then you would like integrate this Recommendation Software or Recommendation Application integrated with your web application. This way even if the user doesn't have the client software installed on his device still based on your search history the context engine can predict what the user might like do at given moment.

I would rather say that you can even execute queries in advance to get the data from the data store and make it available in the user session so that when he actually demands it will be available quickly.