0

Here is my scenario. I have a component which searches some records and while searching, those records are marked locked. I am using JSF-2 and primefaces. My MBean is ViewScoped. Now i have a requirement, while closing the browser, the lock on those records need to be released. I was searching and my best bet appears to be @PostDestroy. So can someone help, whether using PostDestroy is correct approach. Some of the threads on StackOverFlow suggest, PostDestroy doesn't get called on browser close events. I I am not able to find much on PostDestroy. Can someone provide pointers on this approach?

Thanks, Ben

benz
  • 4,561
  • 7
  • 37
  • 68

1 Answers1

0

Your @ViewScoped Bean does not know if the user is closing the browser. For the Bean it does not even matter if the client is a browser or some other HTTP-client.

The lifetime of a @ViewScoped Bean ends normally if your application sends a postback to the next view (see How and when is a view scope bean destroyed in JSF for an exact answer).

You can try to detect a closing browser with the JavaScript window.onunload event but I would not recommend that. Some browsers fire this event on browser close, others not, some fire it on reload etc. (see DOM Window unload event, is it reliable? for more details).

The @PreDestroy annotated Method (not @PostDestroy btw.) may also not be called immediately in some cases. You can only rely that it will be called on a session timeout. Which may be a long time for locking records...

You could release the locked records after a shorter period on your own using some kind of scheduler but I'd recommend to switch to optimistic locking (Don't lock and check if data has changed before you write).

Community
  • 1
  • 1
lefloh
  • 10,653
  • 3
  • 28
  • 50