Friday, June 24, 2011

Single Threading in Vaadin!

Are you developing a Vaadin application for Google App Engine (or you might not be able to spawn threads for any other reason)? Then this post will help you out in creating a more responsive application. This will especially be helpful if you are trying to do heavy backend tasks (Java code as opposed to the client-side JavaScript code). Well, consider it heavy in GAE terms if it is going to take more than 30 seconds.

What to achieve:
I want to update the UI accordingly during a long backend process (e.g. by updating a progress indicator) and let the user intervene to stop it.

The problem:
Without spawning another thread, modifications to the UI components will not take effect until the backend process finishes.

I will try to use Vaadin's capabilities rather than locking myself into Google's task queue API.

What I have done is creating a custom Echo component that simulates a backend to frontend round trip. I have broken down the long process into small chunks. Now I need to call this component from my backend code after doing each chunk of operation. Echo goes off and returns, on return I will resume the process.

Another place this component can be useful is where you want to disable a button while the handler is still working. This could be achieved easily using another thread, but if you cannot spawn threads this is how you might do it: On the button's click listener disable the button and then send an echo. The button is disabled now and you will continue your process in the backend on the response.

There is complete source code available for the custom component and also a sample application that shows how it can be used. Use this command to check it out on your own machine:

svn checkout echosample-read-only
or feel free to browse the repository (here).You can use the jar files provided right away or compile it yourself.

Update: If you seek this solution only to disable a button while processing the click, be aware of this change to the Button that will enable you to call button.setDisableOnClick(false). The feature is to be added to Vaadin 6.7 and you might try the nightly build for an early access.