1

I have an ObjectContext stored in the session. Now I have multiple ajax requests for the same session, all modifying the data of ObjectContext. How do I go about ensuring these requests will be thread safe?

The following documentation suggests that I use context nesting. Can someone give me a concrete example of how this works? Or even an explanation of how nesting context will allow thread-safe requests. Or even a link to some documentation of best practices in these cases. Thanks!

https://cayenne.apache.org/docs/3.1/cayenne-guide/persistent-objects-objectcontext.html

Nesting is useful to create isolated object editing areas (child contexts) that need to all be committed to an intermediate in-memory store (parent context), or rolled back without affecting changes already recorded in the parent. Think cascading GUI dialogs, or parallel AJAX requests coming to the same session.

Edit: I found the following paragraph on the documentation which helped me.

Contexts that are only used to fetch objects from the database and whose objects are never modified by the application can be shared between multiple users (and multiple threads). Contexts that store modified objects should be accessed only by a single user (e.g. a web application user might reuse a context instance between multiple web requests in the same HttpSession, thus carrying uncommitted changes to objects from request to request, until he decides to commit or rollback them). Even for a single user it might make sense to use mutliple ObjectContexts (e.g. request-scoped contexts to allow concurrent requests from the browser that change and commit objects independently)

Tuan
  • 1,476
  • 13
  • 23

1 Answers1

2

If you don't keep uncommitted changes on the server between requests, there is even a simpler solution. Do not use session-scoped ObjectContext. Instead use per-request or even per-method context. Per-method works in a typical case when all your changes introduced by a given request are isolated within a single method call. Then you'd create a context on method entry, load objects (with query or by transferring from another context via 'localObject'), perform changes, commit. After that the context is discarded. E.g.:

public void myActionMethod() {
     ObjectContext peer = serverRuntime.newContext();
     ... do work with objects in 'peer'
     peer.commitChanges();
}

Now, if you do keep uncommitted changes, you can still use per-method contexts, but nested. So the example above becomes this:

public void myActionMethod() {
     ObjectContext nested = serverRuntime.newContext(sessionContext);
     ... do work with objects in 'nested'
     nested.commitChangesToParent();
}
andrus_a
  • 2,528
  • 1
  • 16
  • 10