Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need locking when call VaadinSession getAttribute in Vaadin 7

I know that it is necessary when call setAttribute (link), but what about getAttirbute?

Is this correct?

public Object getMyAttribute() {
    return VaadinSession.getCurrent().getAttribute("myAttribute");
}

Or need locking?

public Object getMyAttribute() {
    try {
        VaadinSession.getCurrent().getLockInstance().lock();
        return VaadinSession.getCurrent().getAttribute("myAttribute");
    } finally {
        VaadinSession.getCurrent().getLockInstance().unlock();
    }
}
like image 269
Krayo Avatar asked Jan 11 '23 05:01

Krayo


1 Answers

Adding to the answer by Patton. While I'm not an expert on this topic, I am posting my understanding after a thorough reading of the doc, and reading this post by Roland Krüger.

Upshot: Moot Question

While I do not know the exact answer to your question, I believe the question is moot.

Let Vaadin 7.1 and later handle the locking for you automatically. The doc says the automatic locking route is preferred over manual locking.

Non-Issue On Main Thread

If accessing the VaadinSession from within the usual main Vaadin user interface thread, then no explicit locking is needed. Vaadin automatically locks the VaadinSession as needed when working in the main thread.

All of your app's state is stored in that session object, so Vaadin is accessing and protecting that session routinely.

Other Threads

Locking is only an issue if accessing the VaadinSession from a background thread, from a thread you started.

Even in this case, Vaadin provides a pair of options where locking is handled automatically if you pass a Runnable to either of these "access" methods:

  • access method on VaadinSession object
  • access method on UI object

If you code affects only the VaadinSession without touching any UI object (user interface, layouts, widget components, and such), then use the first, VaadinSession.access(). On the other hand, if your code affects any UI objects as well as directly addressing the VaadinSession, use the second, UI.access().

Manual Locking Unneeded

So while you can manage the locking during access to the VaadinSession, you need do so only when in a background thread and for some reason you do not want to call either access method. But I cannot imagine any such reason.


For more discussion and a groovy diagram I made, see this similar question, how to put data in session variable and get the data in different page in vaadin?.

like image 51
Basil Bourque Avatar answered Jan 28 '23 21:01

Basil Bourque