public synchronized QueryId createNextQueryId()
    {
        // only generate 100,000 ids per day
        if (counter > 99_999) {
            // wait for the second to rollover
            while (MILLISECONDS.toSeconds(nowInMillis()) == lastTimeInSeconds) {
                Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
            }
            counter = 0;
        }

        // if it has been a second since the last id was generated, generate a new timestamp
        long now = nowInMillis();
        if (MILLISECONDS.toSeconds(now) != lastTimeInSeconds) {
            // generate new timestamp
            lastTimeInSeconds = MILLISECONDS.toSeconds(now);
            lastTimestamp = TIMESTAMP_FORMAT.print(now);

            // if the day has rolled over, restart the counter
            if (MILLISECONDS.toDays(now) != lastTimeInDays) {
                lastTimeInDays = MILLISECONDS.toDays(now);
                counter = 0;
            }
        }

        return new QueryId(String.format("%s_%05d_%s", lastTimestamp, counter++, coordinatorId));
    }
@Test
    public void testCreateNextQueryId()
    {
        TestIdGenerator idGenerator = new TestIdGenerator();

        long millis = new DateTime(2001, 7, 14, 1, 2, 3, 4, DateTimeZone.UTC).getMillis();
        idGenerator.setNow(millis);

        // generate ids to 99,999
        for (int i = 0; i < 100_000; i++) {
            assertEquals(idGenerator.createNextQueryId(), new QueryId(String.format("20010714_010203_%05d_%s", i, idGenerator.getCoordinatorId())));
        }

        // next id will cause counter to roll, but we need to add a second to the time or code will block for ever
        millis += 1000;
        idGenerator.setNow(millis);
        for (int i = 0; i < 100_000; i++) {
            assertEquals(idGenerator.createNextQueryId(), new QueryId(String.format("20010714_010204_%05d_%s", i, idGenerator.getCoordinatorId())));
        }

        // more forward one more second and generate 100 ids
        millis += 1000;
        idGenerator.setNow(millis);
        for (int i = 0; i < 100; i++) {
            assertEquals(idGenerator.createNextQueryId(), new QueryId(String.format("20010714_010205_%05d_%s", i, idGenerator.getCoordinatorId())));
        }

        // now we move to the start of the next day, and the counter should reset
        millis = new DateTime(2001, 7, 15, 0, 0, 0, 0, DateTimeZone.UTC).getMillis();
        idGenerator.setNow(millis);
        for (int i = 0; i < 100_000; i++) {
            assertEquals(idGenerator.createNextQueryId(), new QueryId(String.format("20010715_000000_%05d_%s", i, idGenerator.getCoordinatorId())));
        }
    }