1 import com
.google
.appengine
.api
.datastore
.DatastoreService
;
2 import com
.google
.appengine
.api
.datastore
.DatastoreServiceFactory
;
3 import com
.google
.appengine
.api
.datastore
.Entity
;
4 import com
.google
.appengine
.api
.datastore
.EntityNotFoundException
;
5 import com
.google
.appengine
.api
.datastore
.Key
;
6 import com
.google
.appengine
.api
.datastore
.KeyFactory
;
7 import com
.google
.appengine
.api
.datastore
.Query
;
8 import com
.google
.appengine
.api
.datastore
.Transaction
;
10 import java
.util
.Random
;
13 * This initial implementation simply counts all instances of the
14 * SimpleCounterShard kind in the datastore. The only way to increment the
15 * number of shards is to add another shard by creating another entity in the
18 public class ShardedCounterV1
{
20 private static final DatastoreService ds
= DatastoreServiceFactory
21 .getDatastoreService();
24 * Default number of shards.
26 private static final int NUM_SHARDS
= 20;
29 * A random number generating, for distributing writes across shards.
31 private Random generator
= new Random();
34 * Retrieve the value of this sharded counter.
36 * @return Summed total of all shards' counts
38 public long getCount() {
41 Query query
= new Query("SimpleCounterShard");
42 for (Entity e
: ds
.prepare(query
).asIterable()) {
43 sum
+= (Long
) e
.getProperty("count");
50 * Increment the value of this sharded counter.
52 public void increment() {
53 int shardNum
= generator
.nextInt(NUM_SHARDS
);
54 Key shardKey
= KeyFactory
.createKey("SimpleCounterShard",
55 Integer
.toString(shardNum
));
57 Transaction tx
= ds
.beginTransaction();
60 shard
= ds
.get(tx
, shardKey
);
61 long count
= (Long
) shard
.getProperty("count");
62 shard
.setUnindexedProperty("count", count
+ 1L);
63 } catch (EntityNotFoundException e
) {
64 shard
= new Entity(shardKey
);
65 shard
.setUnindexedProperty("count", 1L);