Posted in Software Engineering

Java Generics Tutorial – Part I – Basics

Generics is a Java feature that was introduced with Java SE 5.0 and, few years after its release, I swear that every Java programmer out there not only heard about it, but used it. There are plenty of both free and commercial resources about Java generics and the best sources I used are:

Despite the wealth of information out there, sometimes it seems to me that many developers still don’t understand the meaning and the implications of Java generics. That’s why I’m trying to summarize the basic information developers need about generics in the simplest possible way.
This blog post is made up of the following parts:

Part I – The Basics
Part II – Subtyping
Part III – Wildcards
Part IV – Bounded Type Variables

The Motivation for Generics

The simplest way to think about Java generics is thinking about a sort of a syntactic sugar that might spare you some casting operation:
List<Apple> box = …;
Apple apple = box.get(0);
The previous code is self-speaking: box is a reference to a List of objects of typeApple. The get method returns an Apple instance an no casting is required. Without generics, this code would have been:
List box = …;
Apple apple = (Apple) box.get(0);
Needless to say, the main advantage of generics is having the compiler keep track of types parameters, perform the type checks and the casting operations: the compiler guarantees that the casts will never fail.

Instead of relying on the programmer to keep track of object types and performing casts, which could lead to failures at runtime difficult to debug and solve, the compiler can now help the programmer enforce a greater number of type checks and detect more failures at compile time.

The Generics Facility

The generics facility introduced the concept of type variable. A type variable, according to the Java Language Specification, is an unqualified identifier introduced by:

  • Generic class declarations.
  • Generic interface declarations.
  • Generic method declarations.
  • Generic constructor declarations.

Generic Classes and Interfaces

A class or an interface is generic if it has one or more type variable. Type variable are delimited by angle brackets and follow the class (or the interface) name:
public interface List<T> extends Collection<T> {
  …
}
Roughly speaking, type variables act as parameters and provide the information the compiler needs to make its checks.

Many classes in the Java library, such as the entire Collections Framework, were modified to be generic. The List interface we’ve used in the first code snippet, for example, is now a generic class. In that snippet, box was a reference to aList<Apple> object, an instance of a class implementing the List interface with one type variable: Apple. The type variable is the parameter that the compiler uses when automatically casting the result of the get method to an Apple reference.

In fact, the new generic signature or the get method of the interface List is:

T get(int index);

The method get returns indeed an object of type T, where T is the type variable specified in the List<T> declaration.

Generic Methods and Constructors

Pretty much the same way, methods and constructors can be generic if they declare one or more type variables.

public static <T> T getFirst(List<T> list)

This method will accept a reference to a List<T> and will return an object of type T.

Examples

You can take advantage of generics in both your own classes or the generic Java library classes.

Type Safety When Writing…

In the following code snippet, for example, we create an instance List<String> of populate it with some data:

List<String> str = new ArrayList<String>();
str.add(“Hello “);
str.add(“World.”);

If we tried to put some other kind of object into the List<String>, the compiler would raise an error:

str.add(1); // won’t compile

… and When Reading

If we pass the List<String> reference around, we’re always guaranteed to retrieve aString object from it:

String myString = str.get(0);

Iterating

Many classes in the library, such as Iterator<T>, have been enhanced and made generic. The iterator() method of the interface List<T> now returns anIterator<T> that can be readily used without casting the objects it returns via its T next() method.

for (Iterator<String> iter = str.iterator(); iter.hasNext();) {
  String s = iter.next();
  System.out.print(s);
}

Using foreach

The for each syntax takes advantage of generics, too. The previous code snippet could be written as:

for (String s: str) {
  System.out.print(s);
}

that is even easier to read and maintain.

Autoboxing and Autounboxing

The autoboxing/autounboxing features of the Java language are automatically used when dealing with generics, as shown in this code snippet:

List<Integer> ints = new ArrayList<Integer>();
ints.add(0);
ints.add(1);
       
int sum = 0;
for (int i : ints) {
  sum += i;
}

Be aware, however, that boxing and unboxing come with a performance penalty so the usual caveats and warnings apply.

Next Steps

In the next part of this post, we will see subtyping relations of generic types.

Part I – The Basics
Part II – Subtyping
Part III – Wildcards
Part IV – Bounded Type Variables

Posted in Software Engineering

Java Generics Tutorial – Part II – Subtyping

Part I – The Basics
Part II – Subtyping
Part III – Wildcards
Part IV – Bounded Type Variables

In Part I we quickly explored the basics of Java generics. In this blog post we will explore how generic types behave in the Java type system. 

Subtypes

In Java, as in other object-oriented typed languages, hierarchies of types can be built:
In Java, a subtype of a type T is either a type that extends T or a type that implements T(if T is an interface) directly or indirectly. Since “being subtype of” is a transitive relation, if a type A is a subtype of B and B is a subtype of C, then A will be a subtype ofC too. In the figure above:
  • FujiApple is a subtype of Apple.
  • Apple is a subtype of Fruit.
  • FujiApple is a subtype of Fruit.
Every Java type will also be subtype of Object.
Every subtype A of a type B may be assigned to a reference of type B:
Apple a = …;
Fruit f = a;

Subtyping of Generic Types

If a reference of an Apple instance can be assigned to a reference of a Fruit, as seen above, then what’s the relation between, let’s say, a List<Apple> and aList<Fruit>? Which one is a subtype of which? More generally, if a type A is a subtype of a type B, how does C<A> and C<B> relate themselves?
Surprisingly, the answer is: in no way. In more formal words, the subtyping relation between generic types is invariant.
This means that the following code snippet is invalid:
List<Apple> apples = …;
List<Fruit> fruits = apples;
and so does the following:
List<Apple> apples;
List<Fruit> fruits = …;
apples = fruits;
But why? Is an apple is a fruit, a box of apples (a list) is also a box of fruits.
In some sense, it is, but types (classes) encapsulate state and operations. What would happen if a box of apples was a box of fruits?
List<Apple> apples = …;
List<Fruit> fruits = apples;
fruits.add(new Strawberry());
If it was, we could add other different subtypes of Fruit into the list and this must be forbidden.
The other way round is more intuitive: a box of fruits is not a box of apples, since it may be a box (List) of other kinds (subtypes) of fruits (Fruit), such as Strawberry.

Is It Really a Problem?

It should not be. The strongest reason for a Java developer to be surprised is the inconsistency between the behavior of arrays and generic types. While the subtyping relations of the latter is invariant, the subtyping relation of the former is covariant: if a type A is a subtype of type B, then A[] is a subtype of B[]:

Apple[] apples = …;
Fruit[] fruits = apples;

But wait! If we repeat the argument exposed in the previous section, we might end up adding strawberries to an array of apples:

Apple[] apples = new Apple[1];
Fruit[] fruits = apples;
fruits[0] = new Strawberry();

The code indeed compiles, but the error will be raised at runtime as an ArrayStoreException. Because of this behavior of arrays, during a store operation, the Java runtime needs to check that the types are compatible. The check, obviously, also adds a performance penalty that you should be aware of.

Once more, generics are safer to use and “correct” this type safety weakness of Java arrays.

In the case you’re now wondering why the subtyping relation for arrays is covariant, I’ll give you the answer that Java Generics and Collections give: if it was invariant, there would be no way of passing a reference to an array of objects of an unknown type (without copying every time to an Object[]) to a method such as:

void sort(Object[] o);

With the advent of generics, this characteristics of arrays is no longer necessary (as we’ll see in the next part of this post) and should indeed by avoided.

Next Steps

In the next post we will see how generic wildcards introduce both covariant and contravariant subtyping relations with generics.

Part I – The Basics
Part II – Subtyping
Part III – Wildcards
Part IV – Bounded Type Variables

Posted in Software Engineering

Java Generics Tutorial – Part IV – Wildcards in Method Signatures and Bounded Type Variables

Part I – The Basics
Part II – Subtyping
Part III – Wildcards
Part IV – Bounded Type Variables

Long time no hear. In the previous parts of this blog post we learned what generics classes and methods are, how they behave in subtyping relations and how wildcardscan be used to provide covariant and contravariant subtyping to generic types.
In this part of this series we will learn what bounded type variables are and the flexibility they provide.

Wildcards in Method Signatures

As seen in Part II of this series, in Java (as in many other typed languages), theSubstitution principle stands: a subtype can be assigned to a reference of any of itssupertypes.

This applies during the assignment of whichever reference, that is, even when passing parameters to a function or storing its result. One of the advantages of this principle, then, is that when defining class hierarchies, “general purpose” methods can be written to handle entire sub-hierarchies, regardless of the class of the specific object instances time being handled. In the Fruit class hierarchy we’ve used so far, a function that accepts a Fruit as a parameter will accept any of its subtypes (such as Apple orStrawberry).

As seen in the previous post, wildcards restore covariant and contravariant subtyping for generic types: using wildcards, then, let the developer write functions that can take advantage of the benefits presented so far.

If, for example, a developer wanted to define a method eat that accepted a List of whichever fruit, it could use the following signature:

void eat(List<? extends Fruit> fruits);

Since a List of whichever subtype of the class Fruit is a subtype of List<? extends Fruit>, the previous method will accept any such list as a parameter. Note that, as explained in the previous section, the Get and Put Principle (or the PECS Rule) will allow you to retrieve objects from such list and assign them to a Fruit reference.

On the other hand, if you wanted to put instances on the list passed as a parameter, you should use the ? super wildcard:

void store(List<? super Fruit> container);

This way, a List of whichever supertype of Fruit could be passed in to the storefunction and you could safely put whichever Fruit subtype into it.

Bounded Type Variables

The flexibility of generics is greater than this, though. Type variables can be bounded, pretty much in the same way wildcards can be (as we’ve seen in Part II). However, type variables cannot be bounded with super, but only with extends. Look at the following signature:

public static <T extends I<T>> void name(Collection<T> t);

It takes a collections of objects whose type is bounded: it must satisfy the T extends I<T> condition. Using bounded type variables may not seem more powerful than wildcards at first, but we’ll detail the differences in a moment.

Let’s suppose some, but not all, fruits in your hierarchy can be juicy as in:

public interface Juicy<T> {
    Juice<T> squeeze();
}


Juicy fruits will implement this interface and publish the squeeze method.

Now, you write a library method that takes a bunch of fruits and squeezes them all. The first signature you could write might be:

<T> List<Juice<T>> squeeze(List<Juicy<T>> fruits);

Using bounded type variables, you would write the following (which, indeed, has got the same erasure of the previous method):

<T extends Juicy<T>> List<Juice<T>> squeeze(List<T> fruits);

So far, so good. But limited. We could use the very same arguments used in the same posts and discover that the squeeze method is not going to work, for example, with a list of red oranges when:

class Orange extends Fruit implements Juicy<Orange>;
class RedOrange extends Orange;

Since we’ve already learned about the PECS principle, we’re going to change the method with:

<T extends Juicy<? super T>> List<Juice<? super T>> squeezeSuperExtends(List<? extends T> fruits);

This method accepts a list of objects whose type extends Juicy<? super T>, that is, in other words, that there must exist a type S such that T extends Juicy<S> and S super T.

Recursive Bounds

Maybe you feel like relaxing the T extends Juicy<? super T> bound. This kind of bound is called recursive bound because the bound that the type T must satisfy depends on T. You can use recursive bounds when needed and also mix-and-match them with other kinds of bounds.

Thus you can, for example, write generic methods with such bounds:

<A extends B<A,C>, C extends D<T>>

Please remember that these examples are only given to illustrate what generics can do. Bounds you’re going to use always depend on the constraints you’re putting into your type hierarchy.

Using Multiple Type Variables

Let’s suppose you want to relax the recursive bound we put on the last version of thesqueeze method. Let’s then suppose that a type T might extend Juicy<S> although T itself does not extends S. The method signature could be:
<T extends Juicy<S>, S> List<Juice<S>> squeezeSuperExtendsWithFruit(List<? extends T> fruits);
This signature has pretty much equivalent to the previous one (since we’re only using Tin the method arguments) but has got one slight advantage: since we’ve declared the generic type S, the method can return List<Juice<S> instead of List<? super T>, which can be useful in some situations, since the compiler will help you identify which type S is according to the method arguments you’ve passed. Since you’re returning a list, chances are you want your caller to be able to get something from it and, as you’ve learned in the previous part, you can only get Object instances from a list such asList<? super T>

You can obviously add more bounds to S, if you need them, such as:

<T extends Juicy<S>, S extends Fruit> List<Juice<S>> squeezeSuperExtendsWithFruit(List<? extends T> fruits);


Multiple Bounds

What if you want to apply multiple bounds on the same type variable? It turns out that you can only write a bound per generic type variable. The following bounds are thus illegal:

<T extends A, T extends B> // illegal

The compiler will fail with a message such as:

T is already defined in…

Multiple bounds must be expressed with a different syntax, which turns out to be a pretty familiar notation:

<T extends A & B>

The previous bounds means that T extends both A and B. Please take into account that, according to the Java Language SecificationChapter 4.4, states that a bound iseither:

  • A type variable.
  • A class.
  • An interface type followed by further interface types.
This means that multiple bounds can only be expressed using interface types. There’s no way of using type variables in a multiple bound and the compiler will fail with a message such as:
A type variable may not be followed by other bounds.
This is not always clear in the documentation I’ve read.
Posted in Software Engineering

Java Generics Tutorial – Part III – Wildcards

The previous posts introduced us to the basics of Java generics y their subtyping relations. In this posts we’ll introduce wildcards and how can covariant andcontravariant subtyping relations be established with generics.

Wildcards

As we’ve seen in the previous post, the subtyping relation of generic types is invariant. Sometimes, though, we’d like to use generic types in the same way we can use ordinary types:

  • Narrowing a reference (covariance).
  • Widening a reference (contravariance


Covariance

Let’s suppose, for example, that we’ve got a set of boxes, each one of a different kind of fruit. We’d like to be able to write methods that could accept a any of them. More formally, given a subtype A of a type B, we’d like to find a way to use a reference (or a method parameter) of type C<B> that could accept instances of C<A>.

To accomplish this task we can use a wildcard with extends, such as in the following example:

List<Apple> apples = new ArrayList<Apple>();
List<? extends Fruit> fruits = apples;

? extends reintroduces covariant subtyping for generics types: Apple is a subtype ofFruit and List<Apple> is a subtype of List<? extends Fruit>.

Contravariance

Let’s now introduce another wildcard: ? super. Given a supertype B of a type A, thenC<B> is a subtype of C<? super A>:

List<Fruit> fruits = new ArrayList<Fruit>();
List<? super Apple> = fruits;


How Can Wildcards Be Used?

Enough theory for now: how can we take advantage of these new constructs?

? extends

Let’s go back to the example we used in Part II when introducing Java array covariance:

Apple[] apples = new Apple[1];
Fruit[] fruits = apples;
fruits[0] = new Strawberry(); 

As we saw, this code compiles but results in a runtime exception when trying to add aStrawberry to an Apple array through a reference to a Fruit array.

Now we can use wildcards to translate this code to its generic counterpart: since Appleis a subtype of Fruit, we will use the ? extends wildcard to be able to assign a reference of a List<Apple> to a reference of a List<? extends Fruit> :

List<Apple> apples = new ArrayList<Apple>();
List<? extends Fruit> fruits = apples;
fruits.add(new Strawberry());


This time, the code won’t compile! The Java compiler now prevents us to add a strawberry to a list of fruits. We will detect the error at compile time and we won’t even need any runtime check (such as in the case of array stores) to ensure that we’re adding to the list a compatible type. The code won’t compile even if we try to add a Fruit instance into the list:

fruits.add(new Fruit());


No way. It comes out that, indeed, you can’t put anything into a structure whose type uses the ? extends wildcard.

The reason is pretty simple, if we think about it: the ? extends T wildcard tells the compiler that we’re dealing with a subtype of the type T, but we cannot know which one. Since there’s no way to tell, and we need to guarantee type safety, you won’t be allowed to put anything inside such a structure. On the other hand, since we know that whichever type it might be, it will be a subtype of T, we can get data out of the structure with the guarantee that it will be a T instance:

Fruit get = fruits.get(0);

? super

What’s the behavior of a type that’s using the ? super wildcard? Let’s start with this:

List<Fruit> fruits = new ArrayList<Fruit>();
List<? super Apple> = fruits;


We know that fruits is a reference to a List of something that is a supertype ofApple. Again, we cannot know which supertype it is, but we know that Apple and any of its subtypes will be assignment compatible with it. Indeed, since such an unknown type will be both an Apple and a GreenApple supertype, we can write:

fruits.add(new Apple());

fruits.add(new GreenApple());

If we try to add whichever Apple supertype, the compiler will complain:

fruits.add(new Fruit());
fruits.add(new Object());


Since we cannot know which supertype it is, we aren’t allowed to add instances of any.

What about getting data out of such a type? It turns out that you the only thing you can get out of it will be Object instances: since we cannot know which supertype it is, the compiler can only guarantee that it will be a reference to an Object, since Object is the supertype of any Java type.

The Get and Put Principle or the PECS Rule

Summarizing the behavior of the ? extends and the ? super wildcards, we draw the following conclusion:

Use the ? extends wildcard if you need to retrieve object from a data structure.
Use the ? super wildcard if you need to put objects in a data structure.
If you need to do both things, don’t use any wildcard.

This is what Maurice Naftalin calls The Get and Put Principle in his Java Generics and Collections and what Joshua Bloch calls The PECS Rule in his Effective Java.

Bloch’s mnemonic, PECS, comes from “Producer Extends, Consumer Super” and is probably easier to remember and use.

Next Steps

In the next post (coming soon), we will put all together in some examples to clarify how generics can be used to help us write cleaner, clearer and more type safe code.

Part I – The Basics
Part II – Subtyping
Part III – Wildcards
Part IV – Bounded Type Variables

Posted in gwt, Software Engineering, Uncategorized

GWT CellTable Example (Using AsyncDataProvider)

http://www.mytechtip.com/2010/11/gwt-celltable-example-using_8168.html

GWT CellTable Example (Using AsyncDataProvider)

GWT version 2.1 has finally been released with the anticipated business level data presentation widgets and other interesting features. CellTable is one of the new widgets that supports pagination. Therefore, there no need to usePagingScrollTable in the gwt incubator or implementations in other third-party libraries.

From the Google official document on how to use data presentation widgets, you can get some examples of using these cell widgets including CellTable. It also includes a simple example of using CellTable with SimplePager to implement pagination. That example uses ListDataProvider which requires all the data that needs to be paged to be set at the client (browser) side. However, in realty, the common practice is to load only one page of data from the server (mostly pulled from a database) to the browser in order to save the bandwidth and improve the response time.

Of course the document indicates there are ways to implement the asynchronized page data loading from remote server.

To illustrate how to use AsyncDataProvider, I modified a simple example from GWT below.

Please note the example do not actually calls the server to get the data. It should be quite easy to modify the example to do so as illustrated in the next code snippet.

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;

public class CellTableExample implements EntryPoint {

/**
   * A simple data type that represents a contact.
   */
private static class Contact {
private final String address;
private final Date birthday;
private final String name;

public Contact(String name, Date birthday, String address) {
this.name = name;
this.birthday = birthday;
this.address = address;
}
}

/**
   * The list of data to display.
   */
@SuppressWarnings("deprecation")
private static final List<Contact> CONTACTS = Arrays.asList(
new Contact("John", new Date(80, 4, 12), "123 Abc Avenue"),
new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
new Contact("Tom", new Date(85, 3, 22), "33 Lance Ln"),
new Contact("Jack", new Date(85, 4, 22), "44 Lance Ln"),
new Contact("Tim", new Date(85, 5, 22), "55 Lance Ln"),
new Contact("Mike", new Date(85, 6, 22), "66 Lance Ln"),
new Contact("George", new Date(46, 6, 6),"77 Lance Ln"));

public void onModuleLoad() {
// Create a CellTable.
final CellTable<Contact> table = new CellTable<Contact>();
// Display 3 rows in one page
table.setPageSize(3);

// Add a text column to show the name.
TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
@Override
public String getValue(Contact object) {
return object.name;
}
};
table.addColumn(nameColumn, "Name");

// Add a date column to show the birthday.
DateCell dateCell = new DateCell();
Column<Contact, Date> dateColumn = new Column<Contact, Date>(dateCell) {
@Override
public Date getValue(Contact object) {
return object.birthday;
}
};
table.addColumn(dateColumn, "Birthday");

// Add a text column to show the address.
TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
@Override
public String getValue(Contact object) {
return object.address;
}
};
table.addColumn(addressColumn, "Address");

// Associate an async data provider to the table
// XXX: Use AsyncCallback in the method onRangeChanged
// to actaully get the data from the server side
AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>() {
@Override
protected void onRangeChanged(HasData<Contact> display) {
int start = display.getVisibleRange().getStart();
int end = start + display.getVisibleRange().getLength();
end = end >= CONTACTS.size() ? CONTACTS.size() : end;
List<Contact> sub = CONTACTS.subList(start, end);
updateRowData(start, sub);
}
};
provider.addDataDisplay(table);
provider.updateRowCount(CONTACTS.size(), true);

SimplePager pager = new SimplePager();
pager.setDisplay(table);

VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);

// Add it to the root panel.
RootPanel.get().add(vp);
}
}

To make remote calls to retrieve table data from the server, The code snippet should look like the following.

// Associate an async data provider to the table
AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>() {
@Override
protected void onRangeChanged(HasData<Contact> display) {
final int start = display.getVisibleRange().getStart();
int length = display.getVisibleRange().getLength();
AsyncCallback<List<Contact>> callback = new AsyncCallback<List<Contact>>() {
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
@Override
public void onSuccess(List<Contact> result) {
updateRowData(start, result);
}
};
// The remote service that should be implemented
remoteService.fetchPage(start, length, callback);
}
};
Posted in JPA, Software Engineering, web application

Don’t use @PersistenceContext in a web app…

source:http://weblogs.java.net/blog/ss141213/archive/2005/12/dont_use_persis_1.html 


I wrote an example web application that uses Java Persistence API. My servlet code looked like this:

public class RegistrationServlet extends HttpServlet {
// inject default EntityManager
@javax.persistence.PersistenceContext private EntityManager em;
@Resource private UserTransaction utx;
public void service ( HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
...
utx.begin();
em.persist(credential);
utx.commit();
...
}
...
}
This code worked, but only by chance. I did not realize that I have committed a horrible mistake in my servlet code. As the servlet spec suggests, unless explicitly mentioned in the deployment descriptor (web.xml) as SingleThreadModel, a single servlet instance by default can be shared to serve multiple requests concurrently. i.e. multiple threads can simultaneously enter the service() method of our servlet because we have not marked the service() assynchronized. As a result multiple threads will share the same PersistenceContext object via the instance variable em. A persistence context is not required to be thread safe as per the spec and is typically designed not to be used concurrently. Because the behavior is timing dependent and I had a tiny example, I did not see this issue during testing.
What is the fix
If we can’t use @PersistenceContext to inject an EntityManager, what is the fix? The fix is to either
use @PersistenceUnit to inject an EntityManagerFactory and use it to get hold of an EntityManager,
or
declare a dependency on an EntityManager and use JNDI to look it up.
The former one is called application managed entity manager because application manages the life cycle (by calling EntityManagerFactory.create & EntityManager.close) where as the later one is called container managed entity manager because container manages life cycle. More discussion on differences between container managed vs. application managed will be done in a later article. Let’s discuss the fix using both the approaches. Let’s discuss each approach using code samples.
Container Managed Entity Manager
There are a couple of ways to use JNDI lookup of entity manager:
a) via annotation:
@PersistenceContext(name="persistence/LogicalName", unitName="ActualPUNameAsItAppearsInPersistence.xml")
public class RegistrationServlet extends HttpServlet {
@Resource private UserTransaction utx;
public void service ( HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
Context envCtx = InitialContext().lookup("java:comp/env");
EntityManager em = (EntityManager) envCtx.lookup("persistence/LogicalName");
...
utx.begin();
em.persist(credential);
utx.commit();
...
}
...
}
Note that there is no injection going on here since the annotation @PersistenceContext appears at the class level. This is an alternative to declaring the persistence context dependency via a persistence-context-ref in web.xml as discussed below (in option #b).
b) via persistence-context-ref in web.xml
In web.xml, add an element like this:
 < persistence-context-ref>
< persistence-context-ref-name>
persistence/LogicalName
</persistence-context-ref>
< persistence-unit-name>
ActualPUNameAsItAppearsInPersistence.xml
</persistence-unit-name>
</persistence-context-ref>
Now do a JNDI lookup in your code as shown below:
public class RegistrationServlet extends HttpServlet {
@Resource private UserTransaction utx;
public void service ( HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
Context envCtx = InitialContext().lookup("java:comp/env");
EntityManager em = (EntityManager) envCtx.lookup("persistence/LogicalName");
...
utx.begin();
em.persist(credential);
utx.commit();
...
}
...
}
While using container managed entity manager (whether option #a or #b is used), we did not call em.close() because container is managing the life cycle of underlying persistence context. We also did not have to call utx.rollback() because web container would automatically rollback a transaction at the end of http request processing if servlet does not end the tx.
Application Managed Entity Manager
public class RegistrationServlet extends HttpServlet {
// inject EntityManagerfactory
@javax.persistence.PersistenceUnit private EntityManagerFactory emf;
@Resource private UserTransaction utx;
public void service ( HttpServletRequest req , HttpServletResponse resp)
throws ServletException, IOException {
EntityManager em = emf.createEntityManager();
try {
...
utx.begin();
em.persist(credential);
utx.commit();
...
} catch (Exception e){
try {
utx.rollback();
} catch (Exception e) {}
} finally {
em.close();
}
}
...
}
See we call close() to close the EntityManager. More over note the use of try catch finally block. Since em.close() can not be called as long as the associated transaction is complete either by calling commit() or rollback(), we have to write those try catch finally.
Is it mentioned any where in the spec?
In Transaction Management chapter, section #4.2.3 of Java EE 5 proposed final draft spec, it is mentioned that:
In web components not implementing SingleThreadModel, transactional resource
objects should not be stored in class instance fields, and should be acquired
and released within the same invocation of the service method.
If you want to draw an analogy with JDBC world then EntityManager is like a Connection, where as EntityManagerFactory is like a DataSource. So EntityManager (or a PersistenceContext) which is a transactional resource should not be stored in a instance field and hence should not be injecte into a web app that does not implement SingleThreadModel.EntityManagerFactory is thread safe, so it can be injected into the servlet.
What is the performance over head?
Creation of a EntityManagerFactory is typically a costly operation. But creation of EntityManager is not. So creating an EntityManager is inside service() does not have negative impact on performance.
What about thread safety of UserTransaction?
If you see the code above, it still injects a UserTransaction object and stores in an instance field. That is not issue because it is a stateless object and can be shared across multiple threads. Looking at the javadocs for UserTransaction, it is clear that it by itself does not represent the transaction object, instead it is an interface to the underlying transaction manager to begin a new transaction and associate that with current thread; and end a transaction associated with current thread.