Runnable (int count, Runnable operation) { return new Runnable() { private final AtomicInteger myCounter = new AtomicInteger(count); @Override public void run() { int currentVal = myCounter.decrementAndGet(); if (currentVal % count == 0) { try { operation.run(); } finally { while (currentVal <= 0 && !myCounter.compareAndSet(currentVal, count + (currentVal % count))) { // restore the counter currentVal = myCounter.get(); } } } } }; }