Elffuss BraidHub

kikocis/java-driver public

Add atomic implementation of timestamp generator.
Changesete0b476ff072a9061f3ff36744d660fd691580e7e91f3c7c44a9ebec57acefe55
Authorolim7t <omichallat+github@gmail.com> · 2014-10-07 21:39 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-08 10:45 +02:00
Parents4104611f66e4

Browse the files at this changeset

9 files changed

added driver-core/src/main/java/com/datastax/driver/core/AbstractTimestampGenerator.java +49 −0
@@ -0,0 +1,49 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import org.slf4j.Logger;
19+import org.slf4j.LoggerFactory;
20+
21+/**
22+ * Base implementation for generators based on {@link System#currentTimeMillis()} and a counter to generate
23+ * the sub-millisecond part.
24+ */
25+abstract class AbstractMonotonicTimestampGenerator implements TimestampGenerator {
26+ private static final Logger logger = LoggerFactory.getLogger(AbstractMonotonicTimestampGenerator.class);
27+
28+ volatile Clock clock = new SystemClock();
29+
30+ protected long computeNext(long last) {
31+ long millis = last / 1000;
32+ long counter = last % 1000;
33+
34+ long now = clock.currentTime();
35+
36+ // System.currentTimeMillis can go backwards on an NTP resync, hence the ">" below
37+ if (millis >= now) {
38+ if (counter == 999)
39+ logger.warn("Sub-millisecond counter overflowed, some query timestamps will not be distinct");
40+ else
41+ counter += 1;
42+ } else {
43+ millis = now;
44+ counter = 0;
45+ }
46+
47+ return millis * 1000 + counter;
48+ }
49+}
added driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java +43 −0
@@ -0,0 +1,43 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.concurrent.atomic.AtomicLong;
19+
20+/**
21+ * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing atomic counter
22+ * to generate the sub-millisecond part.
23+ * <p>
24+ * This implementation guarantees incrementing timestamps among all client threads, provided that no more than
25+ * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()}
26+ * depends on the operating system).
27+ * <p>
28+ * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock
29+ * tick. If you consistently exceed that rate, consider using {@link ThreadLocalMonotonicTimestampGenerator}.
30+ */
31+public class AtomicMonotonicTimestampGenerator extends AbstractMonotonicTimestampGenerator {
32+ private AtomicLong lastRef = new AtomicLong(0);
33+
34+ @Override
35+ public long next() {
36+ while (true) {
37+ long last = lastRef.get();
38+ long next = computeNext(last);
39+ if (lastRef.compareAndSet(last, next))
40+ return next;
41+ }
42+ }
43+}
deleted driver-core/src/main/java/com/datastax/driver/core/CountingTimestampGenerator.java +0 −61
@@ -1,61 +0,0 @@
1-/*
2- * Copyright (C) 2012-2014 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import org.slf4j.Logger;
19-import org.slf4j.LoggerFactory;
20-
21-/**
22- * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing thread-local counter
23- * to generate the sub-millisecond part.
24- */
25-public class CountingTimestampGenerator implements TimestampGenerator {
26- private static final Logger logger = LoggerFactory.getLogger(CountingTimestampGenerator.class);
27-
28- // We're deliberately avoiding an anonymous subclass with initialValue(), because this can introduce
29- // classloader leaks in managed environments like Tomcat
30- private final ThreadLocal<Long> last = new ThreadLocal<Long>();
31-
32- Clock clock = new SystemClock();
33-
34- @Override
35- public long next() {
36- Long micros = this.last.get();
37- if (micros == null)
38- micros = 0L;
39-
40- long millis = micros / 1000;
41- long counter = micros % 1000;
42-
43- long now = clock.currentTime();
44- if (millis == now) {
45- if (counter == 999)
46- // This should not happen: even if System.currentTimeMillis() does not always have millisecond
47- // precision, it's unlikely that a single thread will generate timestamps at that rate
48- logger.warn("Sub-millisecond counter overflowed, some query timestamps will not be distinct");
49- else
50- counter += 1;
51- } else {
52- millis = now;
53- counter = 0;
54- }
55-
56- micros = millis * 1000 + counter;
57-
58- this.last.set(micros);
59- return micros;
60- }
61-}
added driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java +46 −0
@@ -0,0 +1,46 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+
19+/**
20+ * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing thread-local counter
21+ * to generate the sub-millisecond part.
22+ * <p>
23+ * This implementation guarantees incrementing timestamps for a given client thread, provided that no more than
24+ * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()}
25+ * depends on the operating system).
26+ * <p>
27+ * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock
28+ * tick.
29+ */
30+public class ThreadLocalMonotonicTimestampGenerator extends AbstractMonotonicTimestampGenerator {
31+ // We're deliberately avoiding an anonymous subclass with initialValue(), because this can introduce
32+ // classloader leaks in managed environments like Tomcat
33+ private final ThreadLocal<Long> lastRef = new ThreadLocal<Long>();
34+
35+ @Override
36+ public long next() {
37+ Long last = this.lastRef.get();
38+ if (last == null)
39+ last = 0L;
40+
41+ long next = computeNext(last);
42+
43+ this.lastRef.set(next);
44+ return next;
45+ }
46+}
modified driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java +2 −2
@@ -18,8 +18,8 @@
1818 /**
1919 * Generates client-side, microsecond-precision query timestamps.
2020 * <p>
21- * Implementations of this class should guarantee that, for a given thread, successive invocations
22- * of {@link #next()} will yield strictly incrementing timestamps.
21+ * Given that Cassandra uses those timestamps to resolve conflicts, implementations should generate
22+ * incrementing timestamps for successive implementations.
2323 */
2424 public interface TimestampGenerator {
2525 /**
added driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java +66 −0
@@ -0,0 +1,66 @@
1+package com.datastax.driver.core;
2+
3+import java.util.List;
4+import java.util.SortedSet;
5+import java.util.concurrent.ConcurrentSkipListSet;
6+import java.util.concurrent.ExecutionException;
7+import java.util.concurrent.Executors;
8+import java.util.concurrent.TimeUnit;
9+
10+import com.google.common.collect.Lists;
11+import com.google.common.util.concurrent.Futures;
12+import com.google.common.util.concurrent.ListenableFuture;
13+import com.google.common.util.concurrent.ListeningExecutorService;
14+import com.google.common.util.concurrent.MoreExecutors;
15+import org.testng.annotations.Test;
16+
17+import static org.testng.Assert.assertEquals;
18+import static org.testng.Assert.fail;
19+
20+public class AtomicMonotonicTimestampGeneratorTest {
21+ @Test(groups = "unit")
22+ public void should_generate_incrementing_timestamps_for_all_threads() throws InterruptedException {
23+ // Create a generator with a fixed millisecond value
24+ final long fixedTime = 1;
25+ final AtomicMonotonicTimestampGenerator generator = new AtomicMonotonicTimestampGenerator();
26+ generator.clock = new MockClocks.FixedTimeClock(fixedTime);
27+
28+ // Generate 1000 timestamps shared among multiple threads
29+ final int testThreadsCount = 2;
30+ assertEquals(1000 % testThreadsCount, 0);
31+ final SortedSet<Long> allTimestamps = new ConcurrentSkipListSet<Long>();
32+ ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(testThreadsCount));
33+
34+ List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount);
35+ for (int i = 0; i < testThreadsCount; i++) {
36+ futures.add(executor.submit(
37+ new Runnable() {
38+ @Override
39+ public void run() {
40+ for (int i = 0; i < 1000 / testThreadsCount; i++)
41+ allTimestamps.add(generator.next());
42+ }
43+ }));
44+ }
45+ executor.shutdown();
46+ executor.awaitTermination(1, TimeUnit.SECONDS);
47+
48+ try {
49+ Futures.allAsList(futures).get();
50+ } catch (ExecutionException e) {
51+ Throwable cause = e.getCause();
52+ if (cause instanceof AssertionError)
53+ throw (AssertionError)cause;
54+ else
55+ fail("Error in a test thread", cause);
56+ }
57+
58+ // Ensure that the 1000 microseconds for the mocked millisecond value have been generated
59+ int i = 0;
60+ for (Long timestamp : allTimestamps) {
61+ Long expected = fixedTime * 1000 + i;
62+ assertEquals(timestamp, expected);
63+ i += 1;
64+ }
65+ }
66+}
deleted driver-core/src/test/java/com/datastax/driver/core/CountingTimestampGeneratorTest.java +0 −92
@@ -1,92 +0,0 @@
1-package com.datastax.driver.core;
2-
3-import java.util.List;
4-import java.util.concurrent.CountDownLatch;
5-import java.util.concurrent.ExecutionException;
6-import java.util.concurrent.Executors;
7-
8-import com.google.common.collect.Lists;
9-import com.google.common.util.concurrent.Futures;
10-import com.google.common.util.concurrent.ListenableFuture;
11-import com.google.common.util.concurrent.ListeningExecutorService;
12-import com.google.common.util.concurrent.MoreExecutors;
13-import org.testng.annotations.Test;
14-import static org.testng.Assert.assertTrue;
15-import static org.testng.Assert.fail;
16-
17-public class CountingTimestampGeneratorTest {
18- private static final int THREAD_COUNT = 2;
19-
20- @Test(groups = "unit")
21- public void should_generate_incrementing_timestamps() {
22- final CountingTimestampGenerator generator = new CountingTimestampGenerator();
23-
24- ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(THREAD_COUNT));
25- final CountDownLatch latch = new CountDownLatch(1);
26-
27- List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(THREAD_COUNT);
28- for (int i = 0; i < THREAD_COUNT; i++) {
29- futures.add(executor.submit(
30- new Runnable() {
31- @Override
32- public void run() {
33- try {
34- latch.await();
35- } catch (InterruptedException e) {
36- fail("Interrupted while waiting for test start");
37- }
38-
39- long previous = (System.currentTimeMillis() - 1) * 1000;
40-
41- for (int i = 0; i < 10000; i++) {
42- long timestamp = generator.next();
43- assertTrue(timestamp > previous,
44- String.format("iteration %d, timestamp=%d, previous=%d",
45- i, timestamp, previous));
46- previous = timestamp;
47- }
48-
49- assertTrue((System.currentTimeMillis() + 1) * 1000 > previous);
50- }
51- }));
52- }
53- executor.shutdown();
54-
55- latch.countDown();
56- try {
57- Futures.allAsList(futures).get();
58- } catch (InterruptedException e) {
59- fail("Interrupted while getting future");
60- } catch (ExecutionException e) {
61- Throwable cause = e.getCause();
62- if (cause instanceof AssertionError)
63- throw (AssertionError)cause;
64- else
65- fail("Error in a test thread", cause);
66- }
67- }
68-
69- @Test(groups = "unit")
70- public void should_generate_incrementing_timestamps_on_clock_resync() {
71- CountingTimestampGenerator generator = new CountingTimestampGenerator();
72- generator.clock = new BackInTimeClock();
73-
74- long beforeClockResync = generator.next();
75- long afterClockResync = generator.next();
76-
77- System.out.println(beforeClockResync);
78- System.out.println(afterClockResync);
79-
80- assertTrue(beforeClockResync < afterClockResync, "The generated timestamps are not increasing on block resync");
81- }
82-
83- static class BackInTimeClock implements Clock {
84- final long arbitraryTimeStamp = 1412610226270L;
85- int calls;
86-
87- @Override
88- public long currentTime() {
89- return arbitraryTimeStamp - calls++;
90- }
91- }
92-}
added driver-core/src/test/java/com/datastax/driver/core/MockClocks.java +26 −0
@@ -0,0 +1,26 @@
1+package com.datastax.driver.core;
2+
3+class MockClocks {
4+ static class BackInTimeClock implements Clock {
5+ final long arbitraryTimeStamp = 1412610226270L;
6+ int calls;
7+
8+ @Override
9+ public long currentTime() {
10+ return arbitraryTimeStamp - calls++;
11+ }
12+ }
13+
14+ static class FixedTimeClock implements Clock {
15+ final long fixedTime;
16+
17+ public FixedTimeClock(long fixedTime) {
18+ this.fixedTime = fixedTime;
19+ }
20+
21+ @Override
22+ public long currentTime() {
23+ return fixedTime;
24+ }
25+ }
26+}
added driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java +71 −0
@@ -0,0 +1,71 @@
1+package com.datastax.driver.core;
2+
3+import java.util.List;
4+import java.util.concurrent.ExecutionException;
5+import java.util.concurrent.Executors;
6+import java.util.concurrent.TimeUnit;
7+
8+import com.google.common.collect.Lists;
9+import com.google.common.util.concurrent.Futures;
10+import com.google.common.util.concurrent.ListenableFuture;
11+import com.google.common.util.concurrent.ListeningExecutorService;
12+import com.google.common.util.concurrent.MoreExecutors;
13+import org.testng.annotations.Test;
14+import static org.testng.Assert.assertEquals;
15+import static org.testng.Assert.assertTrue;
16+import static org.testng.Assert.fail;
17+
18+public class ThreadLocalMonotonicTimestampGeneratorTest {
19+
20+ @Test(groups = "unit")
21+ public void should_generate_incrementing_timestamps_for_each_thread() throws InterruptedException {
22+ // Create a generator with a fixed millisecond value
23+ final long fixedTime = 1;
24+ final ThreadLocalMonotonicTimestampGenerator generator = new ThreadLocalMonotonicTimestampGenerator();
25+ generator.clock = new MockClocks.FixedTimeClock(fixedTime);
26+
27+ // Generate 1000 timestamps on each thread
28+ int testThreadsCount = 2;
29+ ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(testThreadsCount));
30+
31+ List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount);
32+ for (int i = 0; i < testThreadsCount; i++) {
33+ futures.add(executor.submit(
34+ new Runnable() {
35+ @Override
36+ public void run() {
37+ // Ensure that each thread gets the 1000 microseconds for the mocked millisecond value,
38+ // in order
39+ for (int i = 0; i < 1000; i++)
40+ assertEquals(generator.next(), fixedTime * 1000 + i);
41+ }
42+ }));
43+ }
44+ executor.shutdown();
45+ executor.awaitTermination(1, TimeUnit.SECONDS);
46+
47+ try {
48+ Futures.allAsList(futures).get();
49+ } catch (ExecutionException e) {
50+ Throwable cause = e.getCause();
51+ if (cause instanceof AssertionError)
52+ throw (AssertionError)cause;
53+ else
54+ fail("Error in a test thread", cause);
55+ }
56+ }
57+
58+ @Test(groups = "unit")
59+ public void should_generate_incrementing_timestamps_on_clock_resync() {
60+ ThreadLocalMonotonicTimestampGenerator generator = new ThreadLocalMonotonicTimestampGenerator();
61+ generator.clock = new MockClocks.BackInTimeClock();
62+
63+ long beforeClockResync = generator.next();
64+ long afterClockResync = generator.next();
65+
66+ System.out.println(beforeClockResync);
67+ System.out.println(afterClockResync);
68+
69+ assertTrue(beforeClockResync < afterClockResync, "The generated timestamps are not increasing on block resync");
70+ }
71+}