What is the correct way to atomically increment a counter in App Engine?

I use Java in the Google App Engine and I am most familiar with the Datastore JDO interface. I am trying to implement a simple load counter that stores its data in an App Engine data store.

I expect only a few thousand downloads per month, so the update speed for my counter will be pretty low. Therefore, I am not interested in lowering the counter.

Pragmatically, I could probably ignore the lock and accept that sometimes I lose the update. However, I would like to know how to do it right without losing any updates. I know that in pure Java I would use synchronization, but I do not quite understand what the equivalent mechanism is in the data warehouse.

+4
source share
2 answers

I found this in another answer:

int retries = 0; int NUM_RETRIES = 10; while (true) // break out below { retries++; pm.currentTransaction().begin(); Object obj = pm.getObjectById(getTargetClass(), getKey()); // Make update to obj try { pm.currentTransaction().commit(); break; } catch (JDOCanRetryException ex) { if (retries == NUM_RETRIES) { throw ex; } } } 

Apparently, the commit call throws an exception if the requested object has been updated since the start of the transaction.

0
source

There are several ways to do this, depending on your requirements, including a splinter. Another option is described here .

+1
source

Source: https://habr.com/ru/post/1380297/


All Articles