Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
Heartbeat not closing session
Hi all,
I'm building an application that has to do some stuff in background. To accomplish this I'm using java Timers and TimerTask.
Since these tasks can run for a while, I want to stop them if the user close the browser but I have a problem with Heartbeat interval.
I've set it to 2 and I've read Vaadin waits 3 heatbeats to fail before starting any UI clean up.
Well, my application looks like this
public class WebUI extends UI implements DetachListener
{
@WebServlet(value = "/*", name="WebUIServlet", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = WebUI.class, heartbeatInterval = 2)
public static class WebUIServlet extends VaadinServlet implements SessionDestroyListener
{
@Override
protected void servletInitialized() throws ServletException
{
super.servletInitialized();
getService().addSessionDestroyListener(this);
}
@Override
public void sessionDestroy(SessionDestroyEvent event)
{
// cleanup task(s)
}
}
@Override
protected void init(VaadinRequest request)
{
addDetachListener(this);
// other code...
}
@Override
public void detach(DetachEvent event)
{
// cleanup task(s)
}
}
My questions:
1) Where should I put my cleanup task(s) code? Into sessionDestroy() or detach() method ?
2) Why if I've set heartbeatInterval to 2, instead of wating 6 minutes for UI cleanup, those methods get called after 25/30 minutes?
IMO this is the biggest misunderstanding in the Vaadin framework, even the Book of Vaadin is missing one important point in the UI Closing mechanism description:
Heartbeat mechanism removes other UIs in the same session that are no longer active. The point is here in the same session! There are scenarios, where the UI will close much later than 3*heartbeat interval, or even never:
- If you open a UI, then close it, and do nothing else with the application, it will live until the session expires (this is probably your 25/30 minutes). If your session timeout is set to infinite like for monitoring applications, the UI (and your open resources) disappear never.
- If you open another UI and interact with it, the first UI is cleaned up only if the second UI belongs to the same session. Opening the second UI from another session/browser does not perform any cleanup!
Server-side there is no timer that periodically checks whether the last heartbeat of any UI was more than 3*N seconds ago. If you need to clear the resources or start a background task after the user closes the client, you have to do it in your code. Do not rely on heartbeat mechanism!