ThreadLocal pattern with Vaadin

Dec 10

Sometimes you have the need to access the methods in a class in a static way. Obviously, this is implemented by marking the methods static, but sometimes this isn’t exactly what you need. The downside with static methods is that they usually are stateless, but what if you want them to be stateful? If you add an instance variable to your class, your static method cannot access it unless the variable itself is static. Making the variable static means that the same variable is shared by all threads in the JVM, in other words, you cannot store any class/method states in the variable, unless the same state is shared by every thread in the JVM.

There is a solution which will allow you to have thread specific instance variables which can be accessed by static methods – it is called the ThreadLocal pattern. There is a wiki article which describes the usage of ThreadLocals in Vaadin applications, but I want to show you a slightly different approach which will allow you to have stateful classes whose methods can be accessed in a static way.

Let’s say I have an application which has user specific configuration variables, such as language, theme name and information whether or not to enable advertisements in the application. I’ll start by implementing this class as any other normal class.

Click here to expand the source code

The next step is to modify the class in such a way that we can access its methods statically, we’ll simply add the “static” keyword to each method declaration.

Click here to expand the source code

At this point your IDE should be screaming that your static methods cannot access the instance variables – this is the point where the ThreadLocal patterns comes into play. A ThreadLocal is described in the following way in its class javadoc:

“This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).”

Instead of wrapping each instance variable in a ThreadLocal, I will add a static ThreadLocal variable containing an instance of the class itself. This way I only need one ThreadLocal variable but I’ll still be able to access all the instance variables from the class’s static methods.

Click here to expand the source code

Now to make it all work with Vaadin, I will need to implement the TransactionListener interface. Before implementing the interface, I will add a constructor for the class which takes as an input a Vaadin application instance. The application instance is stored as an instance variable, so that in the transactionStart and transactionEnd methods I can figure out for which application instance the event belonged to. After this I can implement the transactionStart and transactionEnd methods. The start method is responsible for setting a value for the ThreadLocal and the transactionEnd method is responsible for clearing the ThreadLocal at the end of the transaction. If we don’t do this, it could lead to memory leaks and security issues where other users get access to object instances not belong to their own application (due to thread pooling).

Personally, I also prefer to have a static initialize() method which acts as a wrapper for the class constructor and registers the class as a transaction listener to the application. Adding the method is not mandatory, but since the rest of the methods in the class are called statically, then for the sake of consistency I prefer to initialize the class statically as well, secondly, I don’t have to remember to manually register the class as a transaction listener. The final implementation of the class would look like this:

Click here to expand the source code

Now, when I want to use the class in my Vaadin application, all I need to do is to initialize the class in my application and then I’m ready to use the class anywhere I like. Note that you cannot use this class outside Vaadin transactions (http requests), because then the ThreadLocal wouldn’t have a value and it would cause a NullPointerException. This might occur, for example, if you have a background thread running some heavy computations outside the Vaadin transaction and trying to access the ThreadLocal from there.

Click here to expand the source code

Using AppFoundation together with LazyQueryContainer

Nov 29

Prerequisites: Readers are expected to be familiar with AppFoundation (especially its persistence module) and Vaadin containers and its Sortable and Filterable interfaces.

Since the opening of the Vaadin directory, a bunch of really interesting add-ons have emerged there. One interesting add-on is the LazyQueryContainer – it’s a container implementation which fetches data lazily, in other words, data is fetched only when it is needed. It’s by no means the only container which allows lazy fetching of data, but what made this specific container implementation interesting, was that it is licensed under Apache 2.0 license and it won the Vaadin Add-on competition in September.

In this blog post I want to show you how you can combine AppFoundation and LazyQueryContainer to enable lazy data loading in your JPA based application. Be aware, this blog post will be very technical. I will discuss how to combine the LazyQueryContainer with AppFoundation, step by step explaining all the details and providing you with the necessary code examples. At the end of this blog post, I have created a generic LazyQueryContainer which works for any entity type supported by AppFoundation’s persistence module. The container I’m going to write will implement both the sortable and filterable container interfaces. If you are not interested in the implementation details, but rather just want to know how to integrate LazyQueryContainer and AppFoundation to your project, then please wait for my next blog post :)

After downloading the LazyQueryContainer add-on (abbr. LQC) version 1.1.8, I started by taking a look at it and try to figure out what I need to do to be able to integrate it with AppFoundation. Obviously, I’m going to use AppFoundation’s persistence module to implement the actual database connection, so the actual first step is then to try to figure out how to combine LQC and AppFoundation.

By looking at the LQC’s wiki page, I saw that I need to make my own implementations of the Query and QueryFactory interfaces.

The Query interface defines a set of methods for handling data, for example, fetching a subset of entities, getting the size of the container or saving changes made to a set of entities. Implementing this interface was quite straight forward, it is basically just a wrapper for AppFoundation’s facade calls. My implementation is called AFQuery and it’s a generic implementation that works for all entities which extends AppFoundation’s AbstractPojo. At this point I noticed that I will need to make my own implementation of the QueryDefinition interface. A QueryDefinition is an object which describes how the query should be constructed, for example, in which order should the elements be sorted. The LazyQueryContainer contains a default implementation called DefaultQueryDefinition, but that won’t fit my needs. I will later in this blog describe why I wanted to create my own implementation of the QueryDefinition interface, but for now I will satisfy on creating a class called AFQueryDefinition which simply extends the DefaultQueryDefinition. Note that in version 1.2.0 of LQC the DefaultQueryDefinition class was marked as final, so you will need to copy its implementation to your class, the code example uses the old 1.1.8 version of LQC which allows extending of the DefaultQueryDefinition.

Click here to view first version of AFQuery

After implementing the Query interface, I took upon myself the task of implementing the QueryFactory. QueryFactory’s purpose is to instantiates new query objects whenever the container’s state changes or refresh is requested. You see, the Query object is stateful and it only handles one state at a time. This means that it contains information about which entities it should fetch and in which order should the entities be sorted. So, for example, if you want to sort your items in another order, then the query’s state has changed and a new Query object will be needed.

Click to view source code of AFQueryFactory

The implementation of this interface was really easy, it only contains two methods, constructQuery and setQueryDefinition. The latter method takes a new instance of QueryDefinition as input, which in my case will be the AFQueryDefinition I created earlier. In the implementation I check that the given parameter in fact is a AFQueryDefinition and then I store the instance in a class variable for later use. The constructQuery method’s purpose is quite simple, all it needs to do is to create a new Query instance and return it. The method takes two input parameters sortPropertyIds (Object[]) and ascendingStates (boolean[]). These two parameters are familiar from the container’s sort() method. Basically, these two parameters define in which order the items in the container should be sorted. In LazyQueryContainer’s default implementation, these two parameters are passed as arguments to the Query object’s constructor, but my implementation will do it a bit differently. Instead of forwarding the parameters to the Query object, I will instead add a sort() method to the AFQueryDefinition which takes as input the sortPropertyIds and ascendingStates parameters and stores them in class variables.

Click to view source of AFQueryDefinition

The next step is to actually support sorting in the Query object. Since the AFQueryDefinition contains information about the actual query, I think it’s logical that it will be responsible of creating a JPQL query for the AFQuery to use. For this, I will need to make small modifications to the AFQueryDefinition and the AFQuery classes. AFQueryDefinition will have a constructor that takes the entity class as an input parameter and then the toString method will be overridden to return a JPQL query. In AFQuery I will need to change the loadItems method slightly, instead of giving the entity class as a parameter to the JPAFacade’s list() method, I will give it a JPQL query string, one which I will get by calling toString on the query definition object.

Click to view changes in AFQueryDefinition

Click to view changes in AFQuery's loadItems() method

At this point I have created a LazyQueryContainer with AppFoundation binding for fetching any type of entities supported by AppFoundation (in other words, anything extending AbstractPojo). LazyQueryContainer implements Container.Indexed and Container.Sortable interfaces, but not Container.Filterable. I will now show you how to implement the Filterable interface, an interface which we will need in the address book demo application’s search functionality.

Obviously, to be able to implement the interface, I will need to extend the LazyQueryContainer class. By default, the LazyQueryContainer provides you with a different set of constructor methods to choose from. In my extended class (which I will call AFLazyQueryContainer), I will only implement one constructor, it takes as its arguments a QueryDefinition and a QueryFactory. As you probably guessed, these two objects will be instances of our AFQueryDefinition and AFQueryFactory respectively. Next up is implementing the Filterable interface, it has three methods, addContainerFilter, removeAllContainerFilters and removeContainerFilters. I don’t want the container itself to handle the filters, a more logical place to handle them are in the AFQueryDefinition, as it is responsible for creating the JQPL query. Hence, I will start by adding equivalent filter methods to the AFQueryDefinition.

I’ll start by implementing the addContainerFilter method in the query definition. To have a bit better control over the filters, I will create an inner class called Filter. This class will simply hold the information of one specific filter. It will only have four methods: a constructor which takes as its arguments the same parameters as the addContainerFilter method, an overridden toString method which creates a WHERE clause for the JPQL query, a getParam method which constructs the parameter value for the filter (applies wildcards on the filterString) and finally a getParamName which will return the placeholder’s name in the JPQL query. The filter interface’s methods in the query definition will be implemented by using a map between the property id and a list of filters applied to the property id. Basically, I just add and remove Filter objects from the map based on the container calls. The query definition class will also have a createWhereClause() method which creates, well, the where clause for the JPQL query based on the filters assigned. I’ve also created a getParameterMap() method which will return a map between the filter placeholder names and the actual filter strings (this is needed for AppFoundation’s facade calls). This is all I need to do in the AFQueryDefinition. The last thing I need to do is to change the AFQuery’s size() and loadItems() methods’ implementations so that they take into account the filters.

That’s it and I’m done. You can view the final version of each file by clicking on the links below. Please feel free to use the code in your own projects and play around with both AppFoundation and LazyQueryContainer.

Download the source code as a zip file

Adding JPA based persistence to the Address Book Demo

Apr 09

Every Vaadin developer has probably at some point looked at the Address Book Demo. It is a simple application written as an example of how to develop applications with Vaadin. The example is nice, but it is lacking one key feature, the ability to actually store the addresses in a database.

The Vaadin wiki contains an article written by Petter, which shows how to apply JPA based persistence to the address book demo. The article is great and I recommend you to read it, however, I was thinking that I probably could achieve the same task with a more simple approach.

I’ve written a small framework called Application Foundation. Its goal is to provide a simple and lightweight foundation for Vaadin application. With the application foundation framework you get commonly used features such as JPA based persistence, view handling, i18n, authentication and permission management. For this article, I’ll be using the persistence module to provide the JPA based persistence.

Setting up and configuring the project
I’ll start by checkout out the source code of the address book demo and set up my Vaadin project in Eclipse. Next, I’ll download the newest version of Application Foundation (at the time of writing this, the newest version is 1.2). I’ll add the appfoundation.jar to the WEB-INF/lib folder. The application foundation is a server-side only add-on, so you won’t need to recompile your widgetset.

Once I’ve added the appfoundation.jar to my application, I will need to configure the persistence module. The configuration details are explained in the documentation of the persistence
. Once the persistence module is configured, I will create a context listener which starts up the persistence module when the server is started.

Identifying and applying the needed changes
I’ll start by identifying the entities needed in the application. The application only needs one entity and that is the Person class. The required changes are really simple, all I need to do is to annotate the Person class as an entity and make it extend AbstractPojo.

public class Person extends AbstractPojo {

The next modifications I’m going to do is to move the creation of the example data away from the PersonContainer into a class which is executed only once when the server is started. In other words, when the server starts, I want to create a set of test data, persist it and then use the same data in all application instances. I’ll create a class called InitialData which has a static method called init(). I’ll copy the implementation of createWithTestData() method from the PersonContainer and use the exact same implementation in the init() method. Only modifications I’ll make is that I remove the container references and replace the addItem() method with a method which stores the person object into the database.


I previously created a context listener for starting up the persistence module, I’ll add a method call to InitialData.init() in that same context listener. This way my test data is created only when the server is started.

I’ll also have to make small modifications to the PersonContainer. Since the test data has already been created in the context listener, I’ll be wanting to use that data instead of the data created by the container. What I’ll do is fetch all the person objects from the database and populate the container with those objects. The method for populating the container looks like this:

public static void populatedContainer(PersonContainer c) {
   if (c == null) {
   List<Person> persons = FacadeFactory.getFacade().list(Person.class);
   if (persons != null) {
      for (Person p : persons) {

I renamed and refactored the createWithTestData() method, the new implementation looks like this:

public static PersonContainer createAndPopulatedContainer() {
   PersonContainer c = null;
   try {
      c = new PersonContainer();
   } catch (InstantiationException e) {
      // TODO Auto-generated catch block
   } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
   return c;

Next thing I will tackle is the saving of contacts. This means that I want to store to the database any changes made to existing contacts and to store any new contacts created. This is really easy to implement, just two lines of code in the PersonForm’s buttonClick() method. The method contains an if clause for checking if the save button was clicked. At the end of the clause I’ll add the following two lines of code:

Person person = ((BeanItem<Person>) getItemDataSource()).getBean();

The first line fetches the actual Person object from BeanItem which is set as the form’s data source. The second line tells the persistence module to store any changes made to the person object. That’s all, now creating and modifying contacts will work and everything is persisted in the database.

There’s one thing left to do before the example is complete – that task is to handle concurrent modifications. Since every application instance uses the same data, conflicts in editing data may occur. When such a situation occurs, an OptimisticLockingException is thrown. I’ll handle this situation by refreshing the PersonContainer so that all its data is again up-to-date and by notifying the user of what happened. This can be achieved by wrapping the store() method call in a try catch and handling the possible exception.

try {
   Person person = ((BeanItem<Person>) getItemDataSource()).getBean();
} catch (OptimisticLockException e) {
         "Oops, someone else modified the data "
         + "simultaneously, refreshing data",
   PersonContainer c = ((AddressBookApplication) getApplication()).getDataSource();

And I’m all done. Now the address book demo supports JPA based persistence and is able to handle conflicts in concurrent modifications of person contacts.


The following was done to apply JPA based persistence to the Address Book demo.

  • Application Foundation downloaded and configured
  • Made the Person class an entity
  • Creation of test data refactored to another class
  • PersonContainer popoulates itself with data from the database
  • Changes made to contacts stored in the database
  • Implementing handling of concurrent modifications


Visit Our Friends!

A few highly recommended friends...


All entries, chronologically...

Pages List

General info about this blog...