Skip to main content


Showing posts from April, 2011

10 rules about the interview

I attended several interviews recently, and one of my colleagues also gave me very good advice about the interview, I consolidate them with below 10 Rules, hope you can enjoy them:)

Rule 1: Always be in the place 5mins before the interview. If you reach there 30 mins again, it will be bad to just wait there. Or the interviewer may thought you are not good at time management.

Rule 2: Don't show off, Just answer the question

Rule 3: Give the answer directly, and provide and good and bad solution if you have

Rule  4: Being honest, if you don't know, just tell them you don't know, or let the interviewer to tell you more about that, then try your best to answer the question

Rule 5: Make sure you can show interviewer an image of what it is when you try to provide some information to them

Rule 6: Basic knowledge(e.g. data structure and algorithm) is very important

Rule 7: Should be familiar with Design Principle(e.g. Open Closed Rule, Programming to the interface)

Rule 8: Researc…

Struts2 vs Struts 1

Struts 2.x  is very simple as compared to struts 1.x,  few of its excelent features are:
1.  Servlet Dependency:
Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest andHttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.
2.  Action classes
Programming the abstract classes instead of interfaces is one of design issues of struts1 framework that has been resolved in the struts 2 framework.
Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or ma…

The 10 Best Jobs of 2011 |

It is great to know the career I am working with(Software Engineer) is the best job of 2011. According to the best rated job in 2011 is Software Engineer, at least in the US. 200 professions across various industries, skill levels, and salaries have been surveyed to calculate the ranking which is determined by taking the work environment, physical demands, outlook, income and stress into account. Computer Systems Analysts ranked at 5th position, software programmers at 27th position. defines a software engineer as

an engineer who appies the principles of software engineering to the design, development, testing, and evaluation of the software and systems that make computers or anything containing software, such as computer chips, work.Software engineers are employed in different industries such as creation of systems for medical, scientific, or industrial purposes. Thus, there is a high diversity of working environments and industries which require software e…


Memcached is a high-performance, distributed memory object caching system, generic in nature, but originally intended for  use in speeding up dynamic web application by alleviating database load.

Memcached server is an in memory cache that stores anything from binary to text to primitives associated with a key as key-Value pair.  You saves a lot of load of your backend systems, leading to high scalability. since the data is stored in memory, it is generally faster than making an expensive backend call too.

The key in memcached should be less than 255 chars and each value shouldn't exceed 1MB

What it does?
Memcached allows you to take memory from parts of your system where you have more than you need and make it accessible to areas where you have less than you need. With memcached, you can see that all of the servers are looking into the same virtual pool of memory. This means that a given item is always stored and always retrieved from the same location in you entire w…

GWT - Calling remote procedures

Today's browsers include a special JavaScript object called XMLHttpRequest that allows communication between the browser and server without forcing a page refresh . This special JavaScript object is the basis for making browser-based Remote Procedure Calls(RPCs).

GWT provides two tools that sit on top of the XMLHttpRequest object.  The first is the RequestBuilder class, which is essentially a wrapper around this object, although it's a bit more Java-like in its usage.  The second tool, GWT-RPC, is more elaborate and lets you send and receive real Java objects between the client and server.

RequestBuilder class lets you create a request to be submitted to the server, gives you the ability to fire off the request, and provides access to the results sent back from the server.

String url = "/service/search";
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = rb.sendRequest("term=GWT+in+Action",
new RequestCallback() {

GWT - Using JSNI to execute JavaScript from java

Although GWT code is written in Java instead of JavaScript, sometimes you need to write code that can make direct JavaScript calls.  The JavaScript Native Interface(JSNI) lets you execute javaScript from Java as wll as execute Java from Java Script.

Following example passes a Java List object to the method and uses JavaScript to
add two items to it:

public native void fillData (List data)

GWT - Java-to-JavaScript Compiler

The most obvious place to start looking at what GWT provides is t he one tool that defines it. The GWT compiler's responsibility is to convert your Java code into JavaScript code, in much the same way the Java compiler compiles your Java code into bytecode. You compile your project by running the Java program
by, passing it the location of your module definition file along with some other parameters. It will use the JRE emulation library to parse the code. A module is a set of related Java classes and files accompanied by a single configuration file. The module definition typically includes an entry point, which is a class that excutes when the application starts.

The compiler starts with the entry-point class, following dependencies required to compile the Java code. The GWT does not compile everything in the modules, it only includes what is being used.

When your code is compiled to JavaScript, it results in a different JavaScript file for each bro…

Why do scrum?

1. It adapts well to changing requirements at every iteration boundary we make sure that they're still meeting the customers need's and adapt.(Change)
2.The burn down chart, daily standup and frequent contact with the product owner all promote transparency. The goal is that any interested party(whether VP, Software Dev,...) can easily get a good understanding of how the project is progressing without interrupting the team.(Transparency)
3. Every sprint provides another feedback cycle and opportunity to improve introspection. The goal improve both the software and the process with every iteration(Feedback)
4. Because team members talk to each other every day they become more of what other people are working on and how they can help.(Communication)
5. Helps build a team cohesion through collaboration and constant feedback(Team)

Java - Data Structure (Graphs) -part 2

Topological Sorting with Directed Graphs
A topological sort is carried out on a directed graph with no cycles.Such a graph is  called a directed, acyclic graph, often abbreviated DAG

A graph with no cycles is called a tree.

Step 1: Find a vertex that has no successors.
Step 2: Delete this vertex from the graph, and insert its label at the beginning of a list.
Steps 1 and 2 are repeated until all the vertices are gone. At this point, the list shows the
vertices arranged in topological order.

Java - Data Structure (Graphs) -part 1

Graphs are data structures rather like trees. In fact, in a mathematical sense, a tree is kind of graph. In computer programming, however, graphs are used in different ways that trees.
Graphs, on the other hand, often have a shape dictated by a physical problem. for example, nodes in a graph may represent cities, while edges may represent airline flight routes between the cities. 
Definitions: Before going future, we must mention that, when discussing graphs, nodes are called vertices(the singular is vertex). Adjacency:two vertices are said to be adjacent to one another if they are connected by a single edge.
Path: a path is a sequence of edges. 
connected graphs: a graph is said to be connected if there is at least one path from every vertex to every other vertex. 
non-directed graphs mean the edges don't have a direction, you can go either way on them.
The Adjacency List: the other way to represent edges is with an adjacency list.  Actually, an adjacency list a is an array of list.…

Java - Data Structure (Heap)

A priority queue is an ADT offering methods that allow removal of the item with the maximum(or minimum) key value, and sometimes other activities. Can be implemented as an array or heap.
Efficiency: deletion(using array) O(1), insertion(array) O(N)
deletion and insertion (heap): O(LogN)

Heap(be used to implement a priority queue) is a kind of tree. It offers both insertion and deletion in O(logN) time. Thus it's not quite as fast for deletion, but much fast for insertion. It's the method of choice for implementing priority queues where speed is important and there will be many insertion.

don't confuse the term heap, used here for a special kind of binary tree, with the same term used to mean the portion of computer memory available to a programmer with new in languages like Java and C++;

class Node
public int iData; // data item (key)
public Node(int key) // constructor
{ iData = key; }
} // end class Node

class Heap
private Node[] heapArray;
private int maxSize; // si…

Java - Data Structure (Hash Tables)

A hash table is a data structure that offers very fast insertion and searching. No matter how many data items there are, insertion and searching( and sometimes deletion) can take close to constant time: O(1) in Big O notation.

class DataItem
{ // (could have more data)
public int iData; // data item (key)
public DataItem(int ii) // constructor
{ iData = ii; }
} // end class DataItem

nonItem = new DataItem(-1); // deleted item key is -1
DataItem[] hashArray; // array holds hash table

private int hashFunc(int key){
return key % arraySize; // linear probe

public void insert(DataItem item) {
int key = item.iData; //extract key
//hash the key
int hashVal = hashFunc(key);

//until empty cell or -1(nonitem for deleted items)
while(hashArray[hashVal] != null && hashArray[hashVal]l.iData != -1){
hashVal %= arraySize; // wrap around if necessary
} // end while

hashArray[hahVal] = item;
}// end insert()

public DataItem find(int key){
  int hashVal = hashFunc(key);

 //until em…

Java - Data Structure (Binary Trees)

Binary Trees are one of the fundamental data storage structures used in programming. They provide advantages that the data structures we've seen so far cannot.

Why use binary tree?Usually, because it combines the advantages of two other structures: an ordered and array and a linked list. You can search a tree quickly, as you can with an ordered array, and you can also insert and deleted items quickly,as you can with a linked list.

The disadvantage of an ordered array: slow insertion and deletion.
Disadvantage of a linked list: slow searching.

What is a Tree: A tree consists of nodes connected by edges.
                   O -- Node
                 /    \  --- Edges
               /        \
             O         O
            /  \

In computers programs, nodes often represent such entities as people, car parts, airline reservations, and so on.
Edges are likely to be represented in a program by references, if the program is written in Java( or by pointers if the program is written …

Java - Algorithms (Part 2)

Reversion:  It may be amazing that a method can call itself, but why shouldn't it be able to? A method call is a transfer of  control to the start of the method. This transfer of control can take place from within the method as well as from outside.

All this may seem like passing the bulk. Someone tells me to find the 9th triangular number. I know this is 9 plus the 8th triangular number, so I called Martin and ask him to find 8th number.When I hear back from him, I'll add 9 to whatever he tells me and that will be the answer. Martin will ask 7th number from other person. This process continues with each person passing the buck to another one. Where does this buck-passing end? Someone at some point must be able to figure out an answer that doesn't involve asking another person to help them.

The Characteristics of Recursive methods:
. it calls itself
. when it calls itself, it does so to solve a smaller problem. In each successive call of a recursive method to itself, the a…

Java - Data Structure (part 1)

A stack allows access to only one data item: the last item inserted. If you remove this item, then you can access the next-to-last item inserted, and so on.
To insert a data item on the stack is called Push, and to remove a data item from the top of the stack is called Pop(take item from top of the stack). Peek is sometimes useful to be able to read the value from the top of the stack without removing it.

usage: reverse the words; delimiter Matching- the delimiters are the braces '{] and '}, brackets '[' and ']', and parentheses '(' and ')'. Each opening or left delimiter should be matched by a closing or right delimiter;  e.g. a{b[c]d}e

The word queue is British for line, "queue up" means to get in line. Queue is similar to a stack, except that in a queue the first item inserted is the first to be removed(FIFO), while in a stack, the last itme inserted is the first to be removed(LIFO). Methods include insert, remove,peek, isEmpty, isF…

Java - Algorithms

Bubble Sort, the rules as follows:
1. Compare two players
2. If the one on the left is taller, swap them
3. Move one position right.
4.Continue down the line this way until you reach the right end.
class ArrayBub{
private double[] a; // ref to array a
private int nElems; // number of data items

public void bubbleSort(){
int out, in;

for(out=nElems -1; out > 1; out--)
 for(in =0 ; in<out;i++){
 if(a[in]> a[in+1])
  swap(in, in+1);
}//end bubbleSort

private void swap(int one ,int two){
 double temp = a[one];
a[one] = a[two];

Efficiency of the Bubble Sort:
Runs:O(N2) time
(N-1) + (N-2) + ... + 1=N*(N-1)/2
Number of swaps O(N2)

Selection Sort: The shortest player is then swapped with the player on the left end of the line. at position 0. Now the leftmost player is sorted, and won't need to be moved again. Notice that in this algorithm the sorted player accumulated on the left, while in the bubble sort they accumulated on the right.

public void selectionSort()…

Java - generic

Starting with 5.0, Java includes a generic framework for using abstract types in a way that avoids many explicit casts. A generic type is a type that is not defined at compilation time, but becomes fully specified at run time.
public class Pair<K,V>{
K key;
V value;
public void set(K k, V v){
key = k;
value = v;
public K getKey(){return key;}
public String toString(){
return getKey() + "," + getValue()'
public static void main(String[] args){
Pair<String,Integer> p1 = new Pair<String,Integer>();
p1.set(new String("S",new Integer(36));

Pair<User,Double> p2 = new Pair<User,Double>(); p1.set(new User("xu"),new doubule(36));

The actual type parameter can be an arbitrary type. To restrict the type of an actual parameter, we can use an extends clause. e.g. public  class PersonPair<P extends Person>

Java Basic Knowledge - Part 1

public class Card{
// instance variables:
private String number;
//Accessor methods:
public STring getNumber(){return number;}
//Action methods:
public boolean isNumberCorrect(..){}

{  curly brace for the opening of the method body
} curly brace for the closing of the method body
In Java, any set of statements between braces "{" and "}" define a program block;

; semicolon indicating the end of the statement

Data of Java Objects are stored in instance variables(also called fields);

The operations that can act on data, expressing the "messages" objects respond to are called methods;
A method's name combined with the number and types of its parameters is called a method'ssignature, for it takes all these parts to determine the actual method to perform for a certain method call. The signature of a method does not include the type that the method returns;

the syntax for defining a method is as follows:
modifiers type name(typ…

Java - JDBC

"Java DataBase Connectivity" is commonly used as the long form of  the name.  The seven standard steps for querying databases,
1. Load the JDBC driver. To load a driver, you specify the classname of the database driver in the Class.forName method. By doing so, you automatically created a driver instance and register it with the JDBC driver manager. -- triggered the class initialization.

2.Define the connection URL.

String host = "";
String dbName = "someName";
int port = 1234;
String oracleURL = "jdbc:oracle:thin:@" + host +
":" + port + ":" + dbName;

3.Establish the connection

Connection connection =
DriverManager.getConnection(oracleURL, username, password);

4.create a statement object
Statement statement = connection.createStatement();

5.execute a query or update

String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet res…

The RequestDispatcher

Defines an object that receives requests from the clicent and sends them to any //resource(such as a servlet, HTML file , or JSP file) on the server. The servlet container creates the //RequestDispatcher object, which is used as a wrapper around a server resource located at a particular //path or given by a particular name.
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
// in JSp, you can use <jsp:forward page="<%= destination %>" />

An alternative to forward is include. With include, the servlet can combine its output with that of one or more JSP pages. More commonly, the servlet still relies on JSP pages to produce the output, but the servlet invokes different JSP pages to create different sections of the pages.

This approach is most common when your servlets create portal sites that let users specify where on the page they want various pieces of content to be displayed. e.g. as follows,

String firs…

Build an applet

1. PluginApplet.jsp

<jsp:plugin type="applet"
width="370" height="420">

 /** An applet that uses Swing and Java 2D and thus requires
* the Java Plug-in.
public class PluginApplet extends JApplet {
public void init() {


setContentPane(new TextPanel());

3. Customized Panel

public class TextPanel extends JPanel
implements ActionListener {
private JComboBox fontBox;
private DrawingPanel drawingPanel;

public TextPanel() {
GraphicsEnvironment env =

fontBox = new JComboBox(fontNames);
setLayout(new BorderLayout());
JPanel fontPanel = new JPanel();
fontPanel.add(new JLabel("Font:"));
JButton drawButton = new JButton("Draw");


public void actionPerformed(ActionEvent e) {

Implementing MVC from scratch

For simple and moderately complex applications,  implementing MVC from scratch with RequestDispatcher is straightforward and flexible.

The most important point about MVC is the idea of separating the business logic and data access layers from the presentation layer.  Here is a quick summary of the required steps:
1. Define beans to represent the data.
Beans are just Java objects that follow a few simple conventions. Your first step is define beans to represent the results that will be presented to the user
2. Use a servlet to handle requests.
In most cases, the servlet reads request parameters(shorthand using BeanUtils.populateBean)
3. Populate the beans. The servlet invokes business logic(application-specific code) or data-access code to obtain the results. The results are placed in the beans that were defined in step 1.

ValueObject value = new ValueObject(...);
HttpSession session = request.getSession();
session.setAttribute("key", value);

Next, the servlet woul…

java - JavaBeans

Beans are simply Java classes that are written in a standard format, three simple points as follows,
. A bean class must have a zero-argument(default) constructor
. A bean class should have no public instance variables(fields).
. Persistent values should be accessed through methods called getXxx and setXxxx.

Using Beans:

<jsp:useBean id="beanName" class="package.Class" />
comments: Best practice - The JSP page Should never creates the objects. the servlet, not the JSP page, should create all the data objects. So, to guarantee that the JSP will not create objects, you should use
<jsp:useBean .. type = "package.Class" /> instead.

<jsp:getProperty name="beanName" property="propertyName" />

<jsp:setProperty name="beanName" property="propertyName" value="propertyValue" />
<FORM ACTION="SaleEntry.jsp">
Item ID: <INPUT TYPE="TEXT" NAME="itemID"&g…

JSP - General

HTMLcomment that is sent to the client but not displayed by the browser.
<!-- Blah -->

Developercomment that is not sent to the client
<%-- Blah --%>

Expression that is evaluated and sent to the client each time the page is requested:
<%= Java Value %>
Current time: <%= new java.util.Date() %>
Your hostname: <%= request.getRemoteHost() %>

Statement or statements that are executed each time the page is requested:
<% Java Statement %>

String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);

Field or method that becomes part of class definition when page is translated into a servlet:

<%! Field Definition %>
<%! Method Definition %>

private int accessCount = 0;
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");

Directive: A JSP directive affects the overall structure of the servlet that results from the JSP page.  Ther…

Servlet - Session

//returns null if no session already exists for the current client

HttpSession session = request.getSession(false);

// creates a new session if no session already exists
// HttpSession session = request.getSession();

if (session == null) {
} else {

SomeClass value =

if (value == null) { // No such object already in session
value = new SomeClass(...);
session.setAttribute("someIdentifier", value);

removeAttribute(String name)

Servlet - cookie

create cookie:

Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year

read cookie:

/** Given the request object, a name, and a default value,
* this method tries to find the value of the cookie with
* the given name. If no cookie matches the name,
* the default value is returned.
public static String getCookieValue
(HttpServletRequest request,
String cookieName,
String defaultValue) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {

Servlet - Response methods


response.sendError(response.SC_NOT_FOUND, message);

long currentTime = System.currentTimeMillis();
long tenMinutes = 10*60*1000; // In milliseconds
currentTime + tenMinutes);

response.setHeader("Refresh", "5; URL=http://host/path/");

//Building Excel Spreadsheets

PrintWriter out = response.getWriter();

//build jpg file


Servlet - Response

A typical response looks like this:
HTTP/1.1 200 OK
Context-Type: text/html
Header2: ..
(Blank Line)
<!DOCTYPE ...>


Codes in the 100s are informational, indicating that the client should
respond with some other action.
• 200–299
Values in the 200s signify that the request was successful.
• 300–399
Values in the 300s are used for files that have moved and usually
include a Location header indicating the new address.
• 400–499
Values in the 400s indicate an error by the client.
• 500–599
Codes in the 500s signify an error by the server.


A value of 200 (SC_OK) means that everything is fine; the document follows for
GET and POST requests. This status is the default for servlets; if you don’t use
setStatus, you’ll get 200.
202 (Accepted)
A value of 202 (SC_ACCEPTED) tells the client that the request is being acted
upon but processing is not yet complete.

Servlet - gzip

Implementing compression is straightforward since support for the gzip format is built in to the java programming language by classes in

// Change the definition of "out" depending on whether
// or not gzip is supported.
PrintWriter out;
if (GzipUtilities.isGzipSupported(request) &&
!GzipUtilities.isGzipDisabled(request)) {
out = GzipUtilities.getGzipWriter(response);
response.setHeader("Content-Encoding", "gzip");
} else {
out = response.getWriter();


out.close(); // Needed for gzip; optional otherwise.

public static boolean isGzipSupported (HttpServletRequest request) { String encodings = request.getHeader("Accept-Encoding"); return((encodings != null) && (encodings.indexOf("gzip") != -1)); }
/** Return gzipping PrintWriter for response. */ public static PrintWriter getGzipWriter (HttpServletResponse response) throws IOException { return(new PrintWriter (new GZIPOutputStream (response.getOutputStre…

Servlet - http header

GET /servlet/Search?keywords=servlets+jsp HTTP/1.1
Accept: image/gif, image/jpg, */*
Accept-Encoding: gzip
Connection: Keep-Alive
Cookie: userID=id123456
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)

Reading headers is straightforward; just call the getHeader method of HttpServletRequest with the name of the header. This call returns a String if the specified header was supplied in the current request, null otherwise.

getMethod: return GET , POST, HEAD,PUT, AND DELETE.
getRequestURI: "/servlet/search".
getQueryString: would return keywords=servlets+jsp
getProtocol: HTTP 1.1

Servlet - Automaticlly populating java Object from Request Parameters:Form Beans

The getParameter method makes it easy to read incoming request parameters: you use the same method from doGet as from doPost, and the value returned is automatically URL-decoded.  Since the return value of getParameter is String, however, you have to parse the value yourself. Now, in JSP, you can use the JavaBeans component architecture to greatly simplify the process of reading request parameters, parsing the values, and storing the results in Java objects.
The Apache  Jakarta Commons package contains classes that make it easy to build a utility to automatically associate request parameters with bean properties. BeanUtilities.populateBean(Object formBean, HttpServletRequest request); as follows, InsuranceInfo info = new InsuranceInfo(); BeanUtilities.populateBean(info, request);
public class InsuranceInfo { private String name = "No name specified"; private String employeeID = "No ID specified"; private int numChildren = 0; private boolean isMarried = false; publ…

Servlet - general usage

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();

//one param:

// multiple parameters
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =

Java - Servlet general

Servlets are Java Programs that run on Web or applicatoin servers, acting as a middle layer between requests coming from Web browsers or other HTTP clients and databases or applicatoins on the HTTP server.  a somewhat oversimplified view of servlets is that they are Java programs with HTML embedded inside of them.

A somewhat oversimplified view of JSP documents is that they are HTML pages with Java code embedded inside of them.

Life Cycle:
When the servlet is first created, its init method is invoked, so init is where you put one-time setup code. After this, each user request results in a thread that calls the services method of the previously created instance. Multiple concurrent requests normally result in multiple threads calling service simultaneously, although your servlet can implement a special interface(SingleThreadModel) that stipulates that only a single thread is permitted to run at any one time. The service method checks the HTTP request type(GET,POST,DeLETE, etc) and call…

JSTL - core

<%@ taglib prefix="c" uri="" %>

<c:forEach var="qrs1" items="${qry1.rows}">

<c:set var="value" value="${qry2.rows[0].NNN}" />

<c:url value="xxxxx" var="sLink" />
<form method="post" action="${sLink}"

<c:if test="${not empty xxx}">
  do something

    <c:when test="${xxx == XXX}">

JSTL - sql:query

Configure Root.xml file:

  <Resource     auth="Container"     description="Oracle Datasource"     name="jdbc/mydb"     type="javax.sql.DataSource"     driverClassName="oracle.jdbc.driver.OracleDriver"     maxIdle="4"     maxWait="-1"     maxActive="8"     removeAbandoned="true"     logAbandoned="true"     url="%db_url%"     connectionProperties="oracle.jdbc.mapDateToTimestamp=false;"     username="%username%"     password="%password%" /> ....
Use <sql:query>
<%@ taglib prefix="sql" uri="" %> <sql:setDataSource var="mydb" dataSource="jdbc/mydb"/> <sql:query var="qry1" dataSource="${mydb}">    SELECT NA…

Hibernate - managing the persistence context

The persistence context(Session) does many things for you: automatic dirty checking, guaranteed scope of object identity, and so on.

The persistence context is a cache of persistent objects. Every object in persistent state is known to the persistence context, and  a duplicate, a snapshot of each persistent instance, is held in the ache. This snapshot is used internally for dirty checking, to detect any modifications you made to your persistent objects.

Many Hibernate users who ignore this simple fact run into an OutOfmemorryException. This is typically the case when you load thousands of objects in a Session but never intend to modify them. Hibernate still has to create a snapshot of each object in the persistence context cache and keep a reference to the managed object, which can lead to memory exhaustion. (Obviously, you should execute a bulk data operation if you modify thousands of objects.

The persistence context cache never shrinks automatically. To reduce or regain the memory …