Cleaning up threads in UI

I’m running Vaadin in Felix OSGi. My UI is a bundle and contains a Timer thread which produces (fake) data.
When the bundle gets stopped or updated, I want to clean-up that thread.

I thought that detach() would be the correct way but, a post by Henri Sara (sorry can’t find it again) suggests that detach() might not always get called.
Also, I’m not quite sure how the UI (which is registered as a VaadinServlet in the HttpService) gets notified of the pending stop (does it?).

Is there a recommended way to clean-up resources in a UI, or should I implement my own shutdown hook?

Hi Philip,

you could use a destroy method for your bundle.
If you use blueprint, you can write:

<bean id="myUi" class="com.example.MyUi" destroy-method="onDestroy" /> So your class looks like

public class MyUi extends UI {

   // ... init method and stuff

   public void onDestroy() {
       cleanUpThreads();
  }

OK thanks.
I thought maybe the detach() mechanism was the “right” way of doing it, but OK for rolling my own destroy method.
Philipp

Hey Philip,

I was rethinking about it. What I said might not work because you don’t let create your UI objects by the blueprint but more dynamically (every reload creates a new UI), the UIProvider creates a new instance.

So did you find out in which scenarios exactly the detach() method did not work?

Well, if I simply stop my bundle, detach() is not called and the timer still lives and does stuff.
I would expect HttpServlet.destroy() (overridden by VaadinServlet) to be called when the Servlet is unregistered from the HttpService. This should probably be the place to do clean-up. But that’s in the Servlet and not the UI.

How is a UI connected to the Servlet? Can/should Servlet.destroy() call detach on all instances of UI?

Ah, in that way I didn’t think :slight_smile:
That actually is a good question. To be safe, I would create create a BundleActivator and handle the threads in

stop(BundleContext context) If you stop a bundle I don’t think there is a very good messaging down to your UI is being stopped too. Sadly I don’t know what exactly happens in the OSGi bundle lifecycle when a bundle stops.

The Servlet should be a good place too.