package com.yahoo.ycsb.generator;

import java.util.concurrent.locks.ReentrantLock;

/**
 * A CounterGenerator that reports generated integers via lastInt()
 * only after they have been acknowledged.
 */
public class AcknowledgedCounterGenerator extends CounterGenerator
{
	private static final int WINDOW_SIZE = 10000;

	private ReentrantLock lock;
	private boolean[] window;
	private int limit;

	/**
	 * Create a counter that starts at countstart.
	 */
	public AcknowledgedCounterGenerator(int countstart)
	{
		super(countstart);
		lock = new ReentrantLock();
		window = new boolean[WINDOW_SIZE];
		limit = countstart - 1;
	}

	/**
	 * In this generator, the highest acknowledged counter value
	 * (as opposed to the highest generated counter value).
	 */
	@Override
	public int lastInt()
	{
		return limit;
	}

	/**
	 * Make a generated counter value available via lastInt().
	 */
	public void acknowledge(int value)
	{
		if (value > limit + WINDOW_SIZE) {
			throw new RuntimeException("This should be a different exception.");
		}

		window[value % WINDOW_SIZE] = true;

		if (lock.tryLock()) {
			// move a contiguous sequence from the window
			// over to the "limit" variable

			try {
				int index;

				for (index = limit + 1; index <= value; ++index) {
					int slot = index % WINDOW_SIZE;

					if (!window[slot]) {
						break;
					}

					window[slot] = false;
				}

				limit = index - 1;
			} finally {
				lock.unlock();
			}
		}
	}
}

@@ -311,16 +311,18 @@
  = 10000
+00
 ;%0A%0A%09priv
@@ -325,16 +325,22 @@
 private 
+final 
 Reentran
@@ -360,16 +360,22 @@
 private 
+final 
 boolean%5B
@@ -393,16 +393,25 @@
 private 
+volatile 
 int limi
@@ -940,16 +940,92 @@
 lue)%0A%09%7B%0A
+%09%09// read volatile variable to see other threads' changes%0A%09%09limit = limit;%0A%0A
 %09%09if (va
@@ -1089,43 +1089,45 @@
 n(%22T
-his should be a different exception
+oo many unacknowledged insertion keys
 .%22);
@@ -1544,14 +1544,95 @@
 %09%09%09%7D%0A%09%09%7D
+%0A%0A%09%09// write volatile variable to make other threads see changes%0A%09%09limit = limit;
 %0A%09%7D%0A%7D%0A

Use volatile correctly.