How to determine if UI was closed in browser?


I am working on a small home automation project where I am using vaadin. The user has the ability to interact with IoT devices, however sometimes the UI has to be updated even if there is no user interaction because of some other event.

I have set up a separate updater thread, however I am unable to shut it down when the user leaves. This results in stacking uncontrolled threads.

I am using the following slice of code:

addDetachListener(e -> {updater.cleanup();}); Where the updater.cleanup(); takes care of stopping every thread that was started before.

I am testing on Chrome and my issue it that

  • If I refresh the page it works just fine.
  • If I close the tab the DetachEvent does not get fired.
  • If I close the Chrome window the DetachEvent does not get fired.

Is there a better way to determine that the app was closed from the user side?

Thank you in advance, any help is appriciated.

Best Regards,


I don’t think browsers implement any reliable method of determining a close event. The UI is kept alive until it misses three consecutive Heartbeat requests; the default heartbeat is to be 5 minutes, so by that default it’ll take up to 15 minutes to determine that the browser has closed. You can configure the heartbeat to be shorter with the heartBeatInterval param (see
this wiki article
), with obvious side-effects: if you set it to be too low, short network outages can also kill your session.



thank you, exactly the answer I was looking for. I will probably shorten it to about 3 minutes, but at least I have it ensured that wildly running threads will be killed after 9 mins.


There is also this add-on, which is a helper to implement Olli’s answer!addon/cleanupservlet-add-on