Suppose you have two threads calling your code snippet below, both
trying to update the same entity. The first thread to call commit() in
your transaction wins. The second thread will throw a
ConcurrentModificationException upon calling commit().

I created a live demonstration to understand this behavior here:
http://gaetestjig.appspot.com/  (the "Unique Constraint" tab)
And I blogged about it here: 
http://blog.broc.seib.net/2011/06/unique-constraint-in-appengine.html

Your application should take the necessary action if another thread
has already written data to the spot you wanted. In my case, I did not
want to occupy the same spot, so I took that exception as a desired
failure to simulate a "unique constraint". Another application may
want to merge data or something crazy like that.

Broc



On Jan 3, 11:20 pm, Harshad <harshad...@gmail.com> wrote:
> Hi,
>
> I am reading the official GAE documentation on transactions and I
> can't understand when a ConcurrentModificationException is thrown.
>
> Look at one of the examples which I am copy-pasting here:
>
> int retries = 3;
> while (true) {
>     Transaction txn = datastore.beginTransaction();
>     try {
>         Key boardKey = KeyFactory.createKey("MessageBoard",
> boardName);
>         Entity messageBoard = datastore.get(boardKey);
>
>         long count = (Long) messageBoard.getProperty("count");
>         ++count;
>         messageBoard.setProperty("count", count);
>         datastore.put(messageBoard);
>
>         txn.commit();
>         break;
>     } catch (ConcurrentModificationException e) {
>         if (retries == 0) {
>             throw e;
>         }
>         // Allow retry to occur
>         --retries;
>     } finally {
>         if (txn.isActive()) {
>             txn.rollback();
>         }
>     }
>
> }
>
> Now, all the writes to the datastore (in this example) are wrapped
> under a transaction. So why would a ConcurrentModificationException be
> thrown?
>
> Does it happen when some other code which is not wrapped in a
> transaction updates the same entity that is being modified by the
> above code? If I ensure that all code that updates an Entity is always
> wrapped in a transaction, is it guaranteed that I won't get a
> ConcurrentModificationException?
>
> thanks,
> Harshad

-- 
You received this message because you are subscribed to the Google Groups 
"Google App Engine for Java" group.
To post to this group, send email to google-appengine-java@googlegroups.com.
To unsubscribe from this group, send email to 
google-appengine-java+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/google-appengine-java?hl=en.

Reply via email to