/**
  * Encapsulates two threads sharing a sum variable to which both add
  * numbers repeatedly.  Lost updates  are
  * prevented with the use of a `synchronized' block.
  *
  */
public class IntensiveSumNoRC implements Runnable {
   // The two fields below are shared by both threads since
   // there is only ONE object created from this class;
   // `volatile' is no longer needed in the sum variable declaration
   // due to its use inside a `synchronized' block.
   /**
	 * The number of times to call the summation function.
	 */
   private int N = 0;
   /**
	 * The variable to which the two threads add numbers repeatedly.
	 */
   private long sum = 0;

   /**
	 * Constructor.
	 * @param N The number of times to call the summation function.
	 */
   public IntensiveSumNoRC(int N) { this.N = N; }

   /**
	 * The summation function simulates a CPU-intensive addition operation.
	 * @param j The initial value.
	 * @param k The number of times to loop.
	 * @return The total
	 */
   private long fn(long j, int k) {
	  long total = j;
	  for (int i = 1;  i <= k; i++) total += i;
	  return total;
   }

   /**
	 * Code for threads inside this object to execute.
	 */
   public void run() {
	  for (int m = 1; m <= N; m++) {
		 synchronized (this) { // entry protocol
			sum = fn(sum, m);  // critical section: we are working on the shared  variable
		 }                     // exit protocol
	  }
	  
	  System.out.println("sum = " + sum);
   }
}

