/*  Taken from Paul Butcher: Seven Concurrency Models in Seven Weeks
 * Counting, chapter 1, location 373/7299
 * 
 * The increment() method generates four lines of bytecode:
 *   getfield #2
 *   iconst_1
 *   iadd
 *   putfield #2
 * The keyword 'synchronized' on the increment() method will use the intrinsic lock
 * automatically associated with every Java object -- in this case, with Counter counter 
 * object (line 23)
 * 
 * Butcher's text claims this code still may yield "subtle bug"
 * Since there is only one lock (on counter), the bug cannot be deadlock. I don't see the bug.
 * The only other access to counter is via main's call to getCount() -- which happens after
 * both t1 and t2 terminate.
 */
public class CountingFixed {
	
	public static void main (String[] args) throws InterruptedException {
		
		class Counter {
			private int count = 0;
			public synchronized void increment() { ++count; }  // keyword synchronized
			public int getCount() { return count; }
			}
		
		final Counter counter = new Counter();
		
		class CountingThread extends Thread {
			public void run() {
				for (int x = 0; x < 10000; ++x)
					counter.increment();
			}
		}
		
		CountingThread t1 = new CountingThread();
		CountingThread t2 = new CountingThread();
		t1.start();  t2.start();
		t1.join();   t2.join();
		
		System.out.println(counter.getCount() );
	}
}
