Vaadin 7 and ThreadLocal

Hi,

I have a Vaadin project depending on another one. The second one is used as a library and internally it is using a ThreadLocal variable.

My problem is that usually after a short time after using the vaadin project that variable gets reset back to null. I imagine this is related to the way Vaadin handles threads which is not clear to me.

I am instancializing this ThreadLocal in the first line of:

protected void init(VaadinRequest request) {

in my Custom UI class. Is there any better place where I can do this so that the ThreadLocal variable doesn’t get reset to null?

I am not totally sure but I think that in Vaadin 6 if I called this from the Application class this was not happening.

Thank you in advance.

Best,
Francesco

If you set your ThreadLocal only once in your UI’s init()-method, the ThreadLocal’s value will only be valid for the current request. The next request may be served by another thread which has no access to that particular ThreadLocal value. Therefore, the pattern to use ThreadLocals in Vaadin is to set the ThreadLocal at the beginning of a request and unset it when the request has been fully handled. In Vaadin 6 you could use a TerminalListener to achieve that. In Vaadin 7, though, there is no such listener. At least, I haven’t found anything similar in the API yet. Maybe the Vaadin developers can give us a hint at how ThreadLocals can be set/unset in Vaadin 7. It would be nice, for instance, if application developers could use the utility class com.vaadin.util.CurrentInstance. The CurrentInstance variable is cleared by the framework at the end of each request. I did not find a suitable place where I could fill CurrentInstance with my ThreadLocal data at the beginning of a request (as with the TerminalListener in Vaadin 6).

On the other hand, with Vaadin 7’s UI and VaadinServiceSession you already have ThreadLocal variables available. You could use those to store your thread data. Every variable you hold in your session or in the current UI can automatically be accessed through a ThreadLocal variable (e.g. UI.getCurrent()). You only have to keep in mind that data that is stored in the UI object will be duplicated for each browser window/tab as there is one UI object for each browser window that has been opened on your application.