Add a new sharded counter counter example, using the
[gae-samples.git] / sharded-counter-java / src / ShardedCounterV1.java
blobba454c3f9c0c23a37fe4057ca812c76601386b41
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;
12 /**
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
16 * datastore.
18 public class ShardedCounterV1 {
20 private static final DatastoreService ds = DatastoreServiceFactory
21 .getDatastoreService();
23 /**
24 * Default number of shards.
26 private static final int NUM_SHARDS = 20;
28 /**
29 * A random number generating, for distributing writes across shards.
31 private Random generator = new Random();
33 /**
34 * Retrieve the value of this sharded counter.
36 * @return Summed total of all shards' counts
38 public long getCount() {
39 long sum = 0;
41 Query query = new Query("SimpleCounterShard");
42 for (Entity e : ds.prepare(query).asIterable()) {
43 sum += (Long) e.getProperty("count");
46 return sum;
49 /**
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();
58 Entity shard;
59 try {
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);
67 ds.put(tx, shard);
68 tx.commit();