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();
}
}
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.
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.
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.
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
objectaccess
method on UI
objectIf 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()
.
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With