Starting background threads in Vaadin - is it safe?

Hi Guys.

In our Vaadin application, a user can do a search which can take a long time. Rather than freeze the whole UI, I spawn a background thread to do the search, and use the refresher add-on to update the UI with results when finished. This works fine.

However, a colleague upon finding out was all “You can’t start threads in servlets!”. A quick wee search on the web did seem to return a lot of pages that share his opinion.

My questions.

  1. Is there anything wrong with what I have done?

  2. Is there any special cleaning up that I should be aware about? For example, imagine the user closes his browser before the background thread finishes. What eventually happens to this thread? At what point will it be cleaned up?

Thanks for your time!

Cheers,
Lee.

The JEE-spec indeed prohibits the spawning of threads from your application. All threads should be managed by the JEE-server in order to make sure everything funtions correctly and the server doesn’t get messed up with dead or locked threads.

The only correct way around it is to get some kind of thread-pool, thread-factory or executorservice from the JEE-server itself. By not all servers do provide such a service (Tomcat for example doesn’t). So be aware that it is a bad thing to do, program extra careful and do aggressive testing in order to avoid the common pitfalls. At least make your threads “daemons” so that the server will stop normally even if there are still running search-threads.

Thanks.

So, although the JEE spec prohibits it, and its a bad thing to do, I would imagine its also quite a common thing to do?

There are after all core Vaadin components that require this threading to be done (e.g. the ProgressIndicator, the Refresher addon), and their examples demonstrate the starting of threads…

Cheers,
Lee.

For those of us using
Servlets
but not
JEE
, you may indeed spawn threads. There are caveats, so do some reading such as
this
.