Counter Example

This is a version of the example shown in the quick start guide, with some additional notes

@Entity // 1
public class Counter {
        protected int count = 0;
        public synchronised void increment()  { count++; }
        public synchronised int getCount() { return count; }
}

public class Demo {     
        
        public static void main() {
         Session.setActiveStore(new RemoteStore("127.0.0.1",10987));  // 2 
         
         Counter counter = (Counter) store.getRoot("count"); // 3
         
         if(counter = null) {
                counter = new Counter();  // 4
                counter = store.setRootIfNull("count",counter);  // 5
         }

         // 6          
         for(int i=0;i<1000;i++)
                counter.increment();
                
         // 7   
         System.out.println("Counter = " + counter.get();       
         
         
         store.shutdown();   // 8
        }
}
  1. The @Entity Annotation tells Jemm that this is a persistent class.
  2. Set the current Store to be refer to a RemoteStore on localhost:10987
  3. Get the current counter held by the Store.
  4. If there is no counter instance, create a new one.
  5. To ensure that everybody ends up with the same counter user Store.setRootIfNull, if another process has set the counter between the (3) and (5), it will return the set instance, otherwise we it will be set to the one we created in (4)
  6. Use the counter in exactly the same way you would normally.
  7. Print the value
  8. Shutdown the store connection nicely.

Counter is by its nature thread-safe. Using JEMM it is thread-safe across threads in multiple JVMs.