I am trying to port an example of Sharding Counters (code.google.com/appengine/articles/sharding_counters.html) to Java. The only problem is that the Java API does not have a call like Python 'get_by_key_name'. This is the main idea:
Transaction tx = pm.currentTransaction(); Key key = KeyFactory.createKey(CounterShard.class.getSimpleName(), counter + randomIndex); CounterShard shard = pm.getObjectById(CounterShard.class, key); if (shard == null) { // API does not work this way... shard = new CounterShard(key, counter); } shard.increment(); pm.makePersistent(shard); tx.commit();
Unfortunately, this throws a JDOObjectNotFoundException on first start. I can run a query to determine if a counter exists for a given name, but this is not transactional. Another thread could do the same, and in the end both would create an object with the same key.
From what I understand, all operations supported in a transaction (for the Java API) are retrieved and placed. So, how can I lock an object with a key that does not exist yet (i.e. No 'get') and make sure that I am the first and only one to create it?
Mark
source share