Hi I need some advise on managing a background thread.
I have a page which shows the states of some hardware components (drainage valves). The status of the valves can be updated by several sources, some internal to my vaddin application, some not. The status of the valves can be detected through a POJO I have created. I want the web page to continously update itself and refresh the contents of the page based upoon the status of tha valves as read via the POJO.
To do this I have created a invisible progressIndicator with an attached Listener and a background thread that updates the progressIndicator’s value every second. The thread updates the indicator and the indicator calls the listener, the listener then polls the state of the valves and updates the components on the webpage as appropriate. This is all working fine.
My problem is dispossing of the background updater thread when the user leaves the page. I want to kill the thread (via a boolean ‘stop’ flag) when the user either leaves the page or exists the application, or closes the browser.
Can anyone offer advice on how I might accomplish this?
While you could listen for close events, they might not come immediately - especially if e.g. the browser crashes. Application.close() is called when the session times out, but that might be late and you could have many background threads running.
If you want your background threads to be pruned more aggressively, you could perhaps update a timestamp in the background thread whenever the UI makes a request to the server, and check in the tread if the last update was e.g. more than 30 seconds ago (or 5 minutes or whatever). To listen to requests, e.g. implement HttpServletRequestListener in your application class - it is called for all requests from the application UI.
Don’t forget to synchronize all UI updates to the application instance, and all updates of the background thread timestamp to some appropriate object.
Good idea on the timestamp :). I think I’ll go with that. I have also moved the Thread managment into the Application class so only one gets created per user now, they still live longer than I’d want, but using your Timestamp method I should be able to sort that out.