kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 4ba3297e30af55f3de40fc4404e5060bec922dc4b99dda226bff3a6e35bd6efb |
|---|---|
| Author | Alexandre Dutra <alexandre.dutra@datastax.com> · 2016-02-11 14:59 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-06-16 20:05 -07:00 |
| Parents | 7dfccac3d4de |
15 files changed
modified changelog/README.md +1 −0
| @@ -53,6 +53,7 @@ | ||
| 53 | 53 | - [improvement] JAVA-888: Add cluster-wide percentile tracker. |
| 54 | 54 | - [improvement] JAVA-963: Automatically register PercentileTracker from components that use it. |
| 55 | 55 | - [new feature] JAVA-1019: SchemaBuilder support for CREATE/ALTER/DROP KEYSPACE. |
| 56 | +- [bug] JAVA-727: Allow monotonic timestamp generators to drift in the future + use microsecond precision when possible. | |
| 56 | 57 | |
| 57 | 58 | |
| 58 | 59 | ### 3.0.2 |
modified driver-core/pom.xml +21 −6
| @@ -15,7 +15,8 @@ | ||
| 15 | 15 | limitations under the License. |
| 16 | 16 | |
| 17 | 17 | --> |
| 18 | -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 18 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
| 19 | + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | 20 | <modelVersion>4.0.0</modelVersion> |
| 20 | 21 | <parent> |
| 21 | 22 | <groupId>com.datastax.cassandra</groupId> |
| @@ -53,6 +54,12 @@ | ||
| 53 | 54 | <version>${metrics.version}</version> |
| 54 | 55 | </dependency> |
| 55 | 56 | |
| 57 | + <dependency> | |
| 58 | + <groupId>com.github.jnr</groupId> | |
| 59 | + <artifactId>jnr-ffi</artifactId> | |
| 60 | + <version>${jnr-ffi.version}</version> | |
| 61 | + </dependency> | |
| 62 | + | |
| 56 | 63 | <!-- Compression libraries for the protocol. --> |
| 57 | 64 | <!-- Each of them is only a mandatory runtime dependency if you want to use the compression it offers --> |
| 58 | 65 | |
| @@ -186,7 +193,9 @@ | ||
| 186 | 193 | <Bundle-SymbolicName>com.datastax.driver.core</Bundle-SymbolicName> |
| 187 | 194 | <Bundle-Version>${project.version}</Bundle-Version> |
| 188 | 195 | <_include>-osgi.bnd</_include> |
| 189 | - <Import-Package><![CDATA[com.google.common*;version="[16.0.1,20)",*]]></Import-Package> | |
| 196 | + <Import-Package> | |
| 197 | + <!-- JNR does not provide OSGi bundles, so exclude it; the driver can live without it --> | |
| 198 | + <![CDATA[com.google.common*;version="[14.0,20)",!jnr.*,*]]></Import-Package> | |
| 190 | 199 | </instructions> |
| 191 | 200 | <supportedProjectTypes> |
| 192 | 201 | <supportedProjectType>jar</supportedProjectType> |
| @@ -206,7 +215,11 @@ | ||
| 206 | 215 | <manifestLocation>${project.build.directory}/META-INF-shaded</manifestLocation> |
| 207 | 216 | <instructions> |
| 208 | 217 | <Import-Package> |
| 209 | - <![CDATA[com.google.common.*;version="[16.0.1,19)",!io.netty.*,javax.security.cert,*]]></Import-Package> | |
| 218 | + <!-- | |
| 219 | + JNR does not provide OSGi bundles, so exclude it; the driver can live without it | |
| 220 | + Explicitly import javax.security.cert because it's required by Netty, but Netty has been explicitly excluded | |
| 221 | + --> | |
| 222 | + <![CDATA[com.google.common.*;version="[14.0,19)",!jnr.*,!io.netty.*,javax.security.cert,*]]></Import-Package> | |
| 210 | 223 | <Private-Package>com.datastax.shaded.*</Private-Package> |
| 211 | 224 | </instructions> |
| 212 | 225 | </configuration> |
| @@ -239,7 +252,8 @@ | ||
| 239 | 252 | </relocation> |
| 240 | 253 | </relocations> |
| 241 | 254 | <transformers> |
| 242 | - <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer"> | |
| 255 | + <transformer | |
| 256 | + implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer"> | |
| 243 | 257 | <resources> |
| 244 | 258 | <resource>META-INF/MANIFEST.MF</resource> |
| 245 | 259 | <resource>META-INF/io.netty.versions.properties</resource> |
| @@ -256,7 +270,8 @@ | ||
| 256 | 270 | </resources> |
| 257 | 271 | </transformer> |
| 258 | 272 | <!-- Pick up the alternate manifest that was generated by the alternate execution of the bundle plugin --> |
| 259 | - <transformer implementation="org.apache.maven.plugins.shade.resource.IncludeResourceTransformer"> | |
| 273 | + <transformer | |
| 274 | + implementation="org.apache.maven.plugins.shade.resource.IncludeResourceTransformer"> | |
| 260 | 275 | <resource>META-INF/MANIFEST.MF</resource> |
| 261 | 276 | <file>${project.build.directory}/META-INF-shaded/MANIFEST.MF</file> |
| 262 | 277 | </transformer> |
| @@ -287,7 +302,7 @@ | ||
| 287 | 302 | </goals> |
| 288 | 303 | </pluginExecutionFilter> |
| 289 | 304 | <action> |
| 290 | - <ignore /> | |
| 305 | + <ignore/> | |
| 291 | 306 | </action> |
| 292 | 307 | </pluginExecution> |
| 293 | 308 | </pluginExecutions> |
added driver-core/src/main/java/com/datastax/driver/core/AbstractMonotonicTimestampGenerator.java +77 −0
| @@ -0,0 +1,77 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 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 com.google.common.annotations.VisibleForTesting; | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * Base implementation for monotonic timestamp generators. | |
| 22 | + * <p/> | |
| 23 | + * The accuracy of the generated timestamps is largely dependent on the | |
| 24 | + * granularity of the underlying operating system's clock. | |
| 25 | + * <p/> | |
| 26 | + * Generally speaking, this granularity is millisecond, and | |
| 27 | + * the sub-millisecond part is simply a counter that gets incremented | |
| 28 | + * until the next clock tick, as provided by {@link System#currentTimeMillis()}. | |
| 29 | + * <p/> | |
| 30 | + * On some systems, however, it is possible to have a better granularity by using a JNR | |
| 31 | + * call to {@code gettimeofday}. The driver will use this system call automatically whenever | |
| 32 | + * available, unless the system property {@code com.datastax.driver.USE_NATIVE_CLOCK} is | |
| 33 | + * explicitly set to {@code false}. | |
| 34 | + * <p/> | |
| 35 | + * Beware that to guarantee monotonicity, if more than one call to {@link #next()} | |
| 36 | + * is made within the same microsecond, or in the event of a system clock skew, this generator might | |
| 37 | + * return timestamps that drift out in the future. | |
| 38 | + * Whe this happens, {@link #onDrift(long, long)} is invoked. | |
| 39 | + */ | |
| 40 | +public abstract class AbstractMonotonicTimestampGenerator implements TimestampGenerator { | |
| 41 | + | |
| 42 | + @VisibleForTesting | |
| 43 | + volatile Clock clock = ClockFactory.newInstance(); | |
| 44 | + | |
| 45 | + /** | |
| 46 | + * Compute the next timestamp, given the last timestamp previously generated. | |
| 47 | + * <p/> | |
| 48 | + * To guarantee monotonicity, the next timestamp should be strictly greater than the last one. | |
| 49 | + * If the underlying clock fails to generate monotonically increasing timestamps, the generator will simply | |
| 50 | + * increment the previous timestamp, and {@link #onDrift(long, long)} will be invoked. | |
| 51 | + * <p/> | |
| 52 | + * This implementation is inspired by {@code org.apache.cassandra.service.ClientState#getTimestamp()}. | |
| 53 | + * | |
| 54 | + * @param last the last timestamp generated by this generator, in microseconds. | |
| 55 | + * @return the next timestamp to use, in microseconds. | |
| 56 | + */ | |
| 57 | + protected long computeNext(long last) { | |
| 58 | + long currentTick = clock.currentTimeMicros(); | |
| 59 | + if (last >= currentTick) { | |
| 60 | + onDrift(currentTick, last); | |
| 61 | + return last + 1; | |
| 62 | + } | |
| 63 | + return currentTick; | |
| 64 | + } | |
| 65 | + | |
| 66 | + /** | |
| 67 | + * Called when generated timestamps drift into the future compared to the underlying clock (in other words, if | |
| 68 | + * {@code lastTimestamp >= currentTick}). | |
| 69 | + * <p/> | |
| 70 | + * This could happen if timestamps are requested faster than the clock granularity, or on a clock skew (for example | |
| 71 | + * because of a leap second). | |
| 72 | + * | |
| 73 | + * @param currentTick the current clock tick, in microseconds. | |
| 74 | + * @param lastTimestamp the last timestamp that was generated, in microseconds. | |
| 75 | + */ | |
| 76 | + protected abstract void onDrift(long currentTick, long lastTimestamp); | |
| 77 | +} |
deleted driver-core/src/main/java/com/datastax/driver/core/AbstractTimestampGenerator.java +0 −49
| @@ -1,49 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 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 | -} |
modified driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java +29 −10
| @@ -15,22 +15,41 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.util.concurrent.TimeUnit; | |
| 18 | 19 | import java.util.concurrent.atomic.AtomicLong; |
| 19 | 20 | |
| 20 | 21 | /** |
| 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}. | |
| 22 | + * A timestamp generator that guarantees monotonically increasing timestamps among all client threads, and logs warnings | |
| 23 | + * when timestamps drift in the future. | |
| 24 | + * | |
| 25 | + * @see AbstractMonotonicTimestampGenerator | |
| 30 | 26 | */ |
| 31 | -public class AtomicMonotonicTimestampGenerator extends AbstractMonotonicTimestampGenerator { | |
| 27 | +public class AtomicMonotonicTimestampGenerator extends LoggingMonotonicTimestampGenerator { | |
| 28 | + | |
| 32 | 29 | private AtomicLong lastRef = new AtomicLong(0); |
| 33 | 30 | |
| 31 | + /** | |
| 32 | + * Creates a new instance with a warning threshold and warning interval of one second. | |
| 33 | + * | |
| 34 | + * @see #AtomicMonotonicTimestampGenerator(long, TimeUnit, long, TimeUnit) | |
| 35 | + */ | |
| 36 | + public AtomicMonotonicTimestampGenerator() { | |
| 37 | + this(1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); | |
| 38 | + } | |
| 39 | + | |
| 40 | + /** | |
| 41 | + * Creates a new instance. | |
| 42 | + * | |
| 43 | + * @param warningThreshold how far in the future timestamps are allowed to drift before a warning is logged. | |
| 44 | + * @param warningThresholdUnit the unit for {@code warningThreshold}. | |
| 45 | + * @param warningInterval how often the warning will be logged if timestamps keep drifting above the threshold. | |
| 46 | + * @param warningIntervalUnit the unit for {@code warningIntervalUnit}. | |
| 47 | + */ | |
| 48 | + public AtomicMonotonicTimestampGenerator(long warningThreshold, TimeUnit warningThresholdUnit, | |
| 49 | + long warningInterval, TimeUnit warningIntervalUnit) { | |
| 50 | + super(warningThreshold, warningThresholdUnit, warningInterval, warningIntervalUnit); | |
| 51 | + } | |
| 52 | + | |
| 34 | 53 | @Override |
| 35 | 54 | public long next() { |
| 36 | 55 | while (true) { |
modified driver-core/src/main/java/com/datastax/driver/core/Clock.java +104 −9
| @@ -15,25 +15,120 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import org.slf4j.Logger; | |
| 19 | +import org.slf4j.LoggerFactory; | |
| 20 | + | |
| 21 | +import java.util.concurrent.atomic.AtomicReference; | |
| 22 | + | |
| 23 | +import static java.util.concurrent.TimeUnit.*; | |
| 24 | + | |
| 18 | 25 | /** |
| 19 | - * This interface allows us not to have a direct call to {@code System.currentTimeMillis()} for testing purposes | |
| 26 | + * A small abstraction around system clock that aims to provide microsecond precision with the best accuracy possible. | |
| 20 | 27 | */ |
| 21 | 28 | interface Clock { |
| 29 | + | |
| 22 | 30 | /** |
| 23 | - * Returns the current time in milliseconds | |
| 31 | + * Returns the current time in microseconds. | |
| 24 | 32 | * |
| 25 | - * @return the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. | |
| 26 | - * @see System#currentTimeMillis() | |
| 33 | + * @return the difference, measured in microseconds, between the current time and and the Epoch | |
| 34 | + * (that is, midnight, January 1, 1970 UTC). | |
| 27 | 35 | */ |
| 28 | - long currentTime(); | |
| 36 | + long currentTimeMicros(); | |
| 37 | +} | |
| 38 | + | |
| 39 | +/** | |
| 40 | + * Factory that returns the best Clock implementation depending on what native libraries are available in the system. | |
| 41 | + * If LibC is available through JNR, and if the system property {@code com.datastax.driver.USE_NATIVE_CLOCK} is set to {@code true} | |
| 42 | + * (which is the default value), then {@link NativeClock} is returned, otherwise {@link SystemClock} is returned. | |
| 43 | + */ | |
| 44 | +class ClockFactory { | |
| 45 | + | |
| 46 | + private static final Logger LOGGER = LoggerFactory.getLogger(ClockFactory.class); | |
| 47 | + | |
| 48 | + private static final String USE_NATIVE_CLOCK_SYSTEM_PROPERTY = "com.datastax.driver.USE_NATIVE_CLOCK"; | |
| 49 | + | |
| 50 | + static Clock newInstance() { | |
| 51 | + if (Native.isLibCLoaded() && SystemProperties.getBoolean(USE_NATIVE_CLOCK_SYSTEM_PROPERTY, true)) { | |
| 52 | + LOGGER.info("Using native clock to generate timestamps."); | |
| 53 | + return new NativeClock(); | |
| 54 | + } else { | |
| 55 | + LOGGER.info("Using java.lang.System clock to generate timestamps."); | |
| 56 | + return new SystemClock(); | |
| 57 | + } | |
| 58 | + } | |
| 59 | + | |
| 29 | 60 | } |
| 30 | 61 | |
| 31 | 62 | /** |
| 32 | - * Default implementation of a clock that delegate its calls to the system clock. | |
| 63 | + * Default implementation of a clock that delegates its calls to the system clock. | |
| 64 | + * | |
| 65 | + * @see System#currentTimeMillis() | |
| 33 | 66 | */ |
| 34 | 67 | class SystemClock implements Clock { |
| 68 | + | |
| 69 | + @Override | |
| 70 | + public long currentTimeMicros() { | |
| 71 | + return System.currentTimeMillis() * 1000; | |
| 72 | + } | |
| 73 | + | |
| 74 | +} | |
| 75 | + | |
| 76 | +/** | |
| 77 | + * Provides the current time with microseconds precision with some reasonable accuracy through | |
| 78 | + * the use of {@link Native#currentTimeMicros()}. | |
| 79 | + * <p/> | |
| 80 | + * Because calling JNR methods is slightly expensive, | |
| 81 | + * we only call it once per second and add the number of nanoseconds since the last call | |
| 82 | + * to get the current time, which is good enough an accuracy for our purpose (see CASSANDRA-6106). | |
| 83 | + * <p/> | |
| 84 | + * This reduces the cost of the call to {@link NativeClock#currentTimeMicros()} to levels comparable | |
| 85 | + * to those of a call to {@link System#currentTimeMillis()}. | |
| 86 | + */ | |
| 87 | +class NativeClock implements Clock { | |
| 88 | + | |
| 89 | + private static final long ONE_SECOND_NS = NANOSECONDS.convert(1, SECONDS); | |
| 90 | + private static final long ONE_MILLISECOND_NS = NANOSECONDS.convert(1, MILLISECONDS); | |
| 91 | + | |
| 92 | + /** | |
| 93 | + * Records a time in micros along with the System.nanoTime() value at the time the | |
| 94 | + * time is fetched. | |
| 95 | + */ | |
| 96 | + private static class FetchedTime { | |
| 97 | + | |
| 98 | + private final long timeInMicros; | |
| 99 | + private final long nanoTimeAtCheck; | |
| 100 | + | |
| 101 | + private FetchedTime(long timeInMicros, long nanoTimeAtCheck) { | |
| 102 | + this.timeInMicros = timeInMicros; | |
| 103 | + this.nanoTimeAtCheck = nanoTimeAtCheck; | |
| 104 | + } | |
| 105 | + } | |
| 106 | + | |
| 107 | + private final AtomicReference<FetchedTime> lastFetchedTime = new AtomicReference<FetchedTime>(fetchTimeMicros()); | |
| 108 | + | |
| 35 | 109 | @Override |
| 36 | - public long currentTime() { | |
| 37 | - return System.currentTimeMillis(); | |
| 110 | + public long currentTimeMicros() { | |
| 111 | + FetchedTime spec = lastFetchedTime.get(); | |
| 112 | + long curNano = System.nanoTime(); | |
| 113 | + if (curNano > spec.nanoTimeAtCheck + ONE_SECOND_NS) { | |
| 114 | + lastFetchedTime.compareAndSet(spec, spec = fetchTimeMicros()); | |
| 115 | + } | |
| 116 | + return spec.timeInMicros + ((curNano - spec.nanoTimeAtCheck) / 1000); | |
| 117 | + } | |
| 118 | + | |
| 119 | + private static FetchedTime fetchTimeMicros() { | |
| 120 | + // To compensate for the fact that the Native.currentTimeMicros call could take | |
| 121 | + // some time, instead of picking the nano time before the call or after the | |
| 122 | + // call, we take the average of both. | |
| 123 | + long start = System.nanoTime(); | |
| 124 | + long micros = Native.currentTimeMicros(); | |
| 125 | + long end = System.nanoTime(); | |
| 126 | + // If it turns out the call took us more than 1 millisecond (can happen while | |
| 127 | + // the JVM warms up, unlikely otherwise, but no reasons to take risks), fall back | |
| 128 | + // to System.currentTimeMillis() temporarily | |
| 129 | + if ((end - start) > ONE_MILLISECOND_NS) | |
| 130 | + return new FetchedTime(System.currentTimeMillis() * 1000, System.nanoTime()); | |
| 131 | + return new FetchedTime(micros, (end + start) / 2); | |
| 38 | 132 | } |
| 39 | -} | |
| No newline at the end of the file | ||
| 133 | + | |
| 134 | +} |
added driver-core/src/main/java/com/datastax/driver/core/LoggingMonotonicTimestampGenerator.java +76 −0
| @@ -0,0 +1,76 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 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 | +import java.util.concurrent.TimeUnit; | |
| 22 | +import java.util.concurrent.atomic.AtomicLong; | |
| 23 | + | |
| 24 | +import static java.util.concurrent.TimeUnit.MICROSECONDS; | |
| 25 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; | |
| 26 | + | |
| 27 | +/** | |
| 28 | + * A monotonic timestamp generator that logs warnings when timestamps drift in the future | |
| 29 | + * (see this class's constructors and {@link #onDrift(long, long)} for more information). | |
| 30 | + */ | |
| 31 | +public abstract class LoggingMonotonicTimestampGenerator extends AbstractMonotonicTimestampGenerator { | |
| 32 | + private static final Logger LOGGER = LoggerFactory.getLogger(TimestampGenerator.class); | |
| 33 | + | |
| 34 | + private final long warningThresholdMicros; | |
| 35 | + private final long warningIntervalMillis; | |
| 36 | + | |
| 37 | + private final AtomicLong lastDriftWarning = new AtomicLong(Long.MIN_VALUE); | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * Creates a new instance. | |
| 41 | + * | |
| 42 | + * @param warningThreshold how far in the future timestamps are allowed to drift before a warning is logged. | |
| 43 | + * @param warningThresholdUnit the unit for {@code warningThreshold}. | |
| 44 | + * @param warningInterval how often the warning will be logged if timestamps keep drifting above the threshold. | |
| 45 | + * @param warningIntervalUnit the unit for {@code warningIntervalUnit}. | |
| 46 | + */ | |
| 47 | + protected LoggingMonotonicTimestampGenerator( | |
| 48 | + long warningThreshold, TimeUnit warningThresholdUnit, | |
| 49 | + long warningInterval, TimeUnit warningIntervalUnit) { | |
| 50 | + this.warningThresholdMicros = MICROSECONDS.convert(warningThreshold, warningThresholdUnit); | |
| 51 | + this.warningIntervalMillis = MILLISECONDS.convert(warningInterval, warningIntervalUnit); | |
| 52 | + } | |
| 53 | + | |
| 54 | + /** | |
| 55 | + * {@inheritDoc} | |
| 56 | + * <p/> | |
| 57 | + * This implementation logs a warning at regular intervals when timestamps drift more than a specified threshold in | |
| 58 | + * the future. These messages are emitted at {@code WARN} level in the category | |
| 59 | + * {@code com.datastax.driver.core.TimestampGenerator}. | |
| 60 | + * | |
| 61 | + * @param currentTick the current clock tick. | |
| 62 | + * @param lastTimestamp the last timestamp that was generated. | |
| 63 | + */ | |
| 64 | + protected void onDrift(long currentTick, long lastTimestamp) { | |
| 65 | + if (LOGGER.isWarnEnabled() && warningThresholdMicros >= 0 && lastTimestamp > currentTick + warningThresholdMicros) { | |
| 66 | + long now = System.currentTimeMillis(); | |
| 67 | + long lastWarning = lastDriftWarning.get(); | |
| 68 | + if (now > lastWarning + warningIntervalMillis && lastDriftWarning.compareAndSet(lastWarning, now)) { | |
| 69 | + LOGGER.warn( | |
| 70 | + "Clock skew detected: current tick ({}) was {} microseconds behind the last generated timestamp ({}), " + | |
| 71 | + "returned timestamps will be artificially incremented to guarantee monotonicity.", | |
| 72 | + currentTick, lastTimestamp - currentTick, lastTimestamp); | |
| 73 | + } | |
| 74 | + } | |
| 75 | + } | |
| 76 | +} |
added driver-core/src/main/java/com/datastax/driver/core/Native.java +109 −0
| @@ -0,0 +1,109 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 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 jnr.ffi.LibraryLoader; | |
| 19 | +import jnr.ffi.Pointer; | |
| 20 | +import jnr.ffi.Runtime; | |
| 21 | +import jnr.ffi.Struct; | |
| 22 | +import jnr.ffi.annotations.Out; | |
| 23 | +import jnr.ffi.annotations.Transient; | |
| 24 | +import org.slf4j.Logger; | |
| 25 | +import org.slf4j.LoggerFactory; | |
| 26 | + | |
| 27 | +/** | |
| 28 | + * Helper class to deal with native system call through JNR. | |
| 29 | + */ | |
| 30 | +class Native { | |
| 31 | + | |
| 32 | + private static final Logger LOGGER = LoggerFactory.getLogger(Native.class); | |
| 33 | + | |
| 34 | + /** | |
| 35 | + * Interface for LIBC calls through JNR. | |
| 36 | + * Note that this interface must be declared public. | |
| 37 | + */ | |
| 38 | + public interface LibC { | |
| 39 | + | |
| 40 | + /** | |
| 41 | + * Timeval struct. | |
| 42 | + * | |
| 43 | + * @see <a href="http://man7.org/linux/man-pages/man2/settimeofday.2.html">GETTIMEOFDAY(2)</a> | |
| 44 | + */ | |
| 45 | + class Timeval extends Struct { | |
| 46 | + | |
| 47 | + public final time_t tv_sec = new time_t(); | |
| 48 | + | |
| 49 | + public final Unsigned32 tv_usec = new Unsigned32(); | |
| 50 | + | |
| 51 | + public Timeval(Runtime runtime) { | |
| 52 | + super(runtime); | |
| 53 | + } | |
| 54 | + } | |
| 55 | + | |
| 56 | + /** | |
| 57 | + * JNR call to {@code gettimeofday}. | |
| 58 | + * | |
| 59 | + * @param tv Timeval struct | |
| 60 | + * @param unused Timezone struct (unused) | |
| 61 | + * @return 0 for success, or -1 for failure | |
| 62 | + * @see <a href="http://man7.org/linux/man-pages/man2/settimeofday.2.html">GETTIMEOFDAY(2)</a> | |
| 63 | + */ | |
| 64 | + int gettimeofday(@Out @Transient Timeval tv, Pointer unused); | |
| 65 | + } | |
| 66 | + | |
| 67 | + private static final LibC LIB_C; | |
| 68 | + | |
| 69 | + private static final Runtime LIB_C_RUNTIME; | |
| 70 | + | |
| 71 | + static { | |
| 72 | + LibC libc = null; | |
| 73 | + Runtime runtime = null; | |
| 74 | + try { | |
| 75 | + libc = LibraryLoader.create(LibC.class).load("c"); | |
| 76 | + runtime = Runtime.getRuntime(libc); | |
| 77 | + } catch (Throwable t) { | |
| 78 | + if (LOGGER.isDebugEnabled()) | |
| 79 | + LOGGER.debug("Could not load JNR LibC Library, native calls will not be available", t); | |
| 80 | + else | |
| 81 | + LOGGER.info("Could not load JNR LibC Library, native calls will not be available (set this logger level to DEBUG to see the full stack trace)"); | |
| 82 | + } | |
| 83 | + LIB_C = libc; | |
| 84 | + LIB_C_RUNTIME = runtime; | |
| 85 | + } | |
| 86 | + | |
| 87 | + /** | |
| 88 | + * Returns true if LibC could be loaded with JNR. | |
| 89 | + * | |
| 90 | + * @return true if LibC could be loaded with JNR, false otherwise. | |
| 91 | + */ | |
| 92 | + static boolean isLibCLoaded() { | |
| 93 | + return LIB_C_RUNTIME != null; | |
| 94 | + } | |
| 95 | + | |
| 96 | + /** | |
| 97 | + * Returns the current timestamp with microsecond precision | |
| 98 | + * via a system call to {@code gettimeofday}. | |
| 99 | + * | |
| 100 | + * @return the current timestamp with microsecond precision. | |
| 101 | + */ | |
| 102 | + static long currentTimeMicros() { | |
| 103 | + LibC.Timeval tv = new LibC.Timeval(LIB_C_RUNTIME); | |
| 104 | + if (LIB_C.gettimeofday(tv, null) != 0) | |
| 105 | + LOGGER.error("gettimeofday failed"); | |
| 106 | + return tv.tv_sec.get() * 1000000 + tv.tv_usec.get(); | |
| 107 | + } | |
| 108 | + | |
| 109 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java +33 −9
| @@ -16,22 +16,46 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | |
| 19 | +import java.util.concurrent.TimeUnit; | |
| 20 | + | |
| 19 | 21 | /** |
| 20 | - * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing thread-local counter | |
| 21 | - * to generate the sub-millisecond part. | |
| 22 | + * A timestamp generator that guarantees monotonically increasing timestamps on a per-thread basis, and logs warnings | |
| 23 | + * when timestamps drift in the future. | |
| 22 | 24 | * <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. | |
| 25 | + * Beware that there is a risk of timestamp collision with this generator when accessed | |
| 26 | + * by more than one thread at a time; only use it when threads are not in direct competition | |
| 27 | + * for timestamp ties (i.e., they are executing independent statements). | |
| 28 | + * | |
| 29 | + * @see AbstractMonotonicTimestampGenerator | |
| 29 | 30 | */ |
| 30 | -public class ThreadLocalMonotonicTimestampGenerator extends AbstractMonotonicTimestampGenerator { | |
| 31 | +public class ThreadLocalMonotonicTimestampGenerator extends LoggingMonotonicTimestampGenerator { | |
| 32 | + | |
| 31 | 33 | // We're deliberately avoiding an anonymous subclass with initialValue(), because this can introduce |
| 32 | 34 | // classloader leaks in managed environments like Tomcat |
| 33 | 35 | private final ThreadLocal<Long> lastRef = new ThreadLocal<Long>(); |
| 34 | 36 | |
| 37 | + /** | |
| 38 | + * Creates a new instance with a warning threshold and warning interval of one second. | |
| 39 | + * | |
| 40 | + * @see #ThreadLocalMonotonicTimestampGenerator(long, TimeUnit, long, TimeUnit) | |
| 41 | + */ | |
| 42 | + public ThreadLocalMonotonicTimestampGenerator() { | |
| 43 | + this(1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); | |
| 44 | + } | |
| 45 | + | |
| 46 | + /** | |
| 47 | + * Creates a new instance. | |
| 48 | + * | |
| 49 | + * @param warningThreshold how far in the future timestamps are allowed to drift before a warning is logged. | |
| 50 | + * @param warningThresholdUnit the unit for {@code warningThreshold}. | |
| 51 | + * @param warningInterval how often the warning will be logged if timestamps keep drifting above the threshold. | |
| 52 | + * @param warningIntervalUnit the unit for {@code warningIntervalUnit}. | |
| 53 | + */ | |
| 54 | + public ThreadLocalMonotonicTimestampGenerator(long warningThreshold, TimeUnit warningThresholdUnit, | |
| 55 | + long warningInterval, TimeUnit warningIntervalUnit) { | |
| 56 | + super(warningThreshold, warningThresholdUnit, warningInterval, warningIntervalUnit); | |
| 57 | + } | |
| 58 | + | |
| 35 | 59 | @Override |
| 36 | 60 | public long next() { |
| 37 | 61 | Long last = this.lastRef.get(); |
modified driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java +9 −1
| @@ -19,11 +19,19 @@ | ||
| 19 | 19 | * Generates client-side, microsecond-precision query timestamps. |
| 20 | 20 | * <p/> |
| 21 | 21 | * Given that Cassandra uses those timestamps to resolve conflicts, implementations should generate |
| 22 | - * incrementing timestamps for successive implementations. | |
| 22 | + * monotonically increasing timestamps for successive invocations of {@link #next()}. | |
| 23 | 23 | */ |
| 24 | 24 | public interface TimestampGenerator { |
| 25 | + | |
| 25 | 26 | /** |
| 26 | 27 | * Returns the next timestamp. |
| 28 | + * <p/> | |
| 29 | + * Implementors should enforce increasing monotonicity of timestamps, that is, | |
| 30 | + * a timestamp returned should always be strictly greater that any previously returned | |
| 31 | + * timestamp. | |
| 32 | + * <p/> | |
| 33 | + * Implementors should strive to achieve microsecond precision in the best possible way, | |
| 34 | + * which is usually largely dependent on the underlying operating system's capabilities. | |
| 27 | 35 | * |
| 28 | 36 | * @return the next timestamp (in microseconds). If it equals {@link Long#MIN_VALUE}, it won't be |
| 29 | 37 | * sent by the driver, letting Cassandra generate a server-side timestamp. |
modified driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java +48 −34
| @@ -20,6 +20,8 @@ | ||
| 20 | 20 | import com.google.common.util.concurrent.ListenableFuture; |
| 21 | 21 | import com.google.common.util.concurrent.ListeningExecutorService; |
| 22 | 22 | import com.google.common.util.concurrent.MoreExecutors; |
| 23 | +import org.apache.log4j.Level; | |
| 24 | +import org.apache.log4j.Logger; | |
| 23 | 25 | import org.testng.annotations.Test; |
| 24 | 26 | |
| 25 | 27 | import java.util.List; |
| @@ -33,6 +35,7 @@ | ||
| 33 | 35 | import static org.testng.Assert.fail; |
| 34 | 36 | |
| 35 | 37 | public class AtomicMonotonicTimestampGeneratorTest { |
| 38 | + | |
| 36 | 39 | @Test(groups = "unit") |
| 37 | 40 | public void should_generate_incrementing_timestamps_for_all_threads() throws InterruptedException { |
| 38 | 41 | // Create a generator with a fixed millisecond value |
| @@ -40,42 +43,53 @@ | ||
| 40 | 43 | final AtomicMonotonicTimestampGenerator generator = new AtomicMonotonicTimestampGenerator(); |
| 41 | 44 | generator.clock = new MockClocks.FixedTimeClock(fixedTime); |
| 42 | 45 | |
| 43 | - // Generate 1000 timestamps shared among multiple threads | |
| 44 | - final int testThreadsCount = 2; | |
| 45 | - assertEquals(1000 % testThreadsCount, 0); | |
| 46 | - final SortedSet<Long> allTimestamps = new ConcurrentSkipListSet<Long>(); | |
| 47 | - ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(testThreadsCount)); | |
| 48 | - | |
| 49 | - List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount); | |
| 50 | - for (int i = 0; i < testThreadsCount; i++) { | |
| 51 | - futures.add(executor.submit( | |
| 52 | - new Runnable() { | |
| 53 | - @Override | |
| 54 | - public void run() { | |
| 55 | - for (int i = 0; i < 1000 / testThreadsCount; i++) | |
| 56 | - allTimestamps.add(generator.next()); | |
| 57 | - } | |
| 58 | - })); | |
| 59 | - } | |
| 60 | - executor.shutdown(); | |
| 61 | - executor.awaitTermination(1, TimeUnit.SECONDS); | |
| 46 | + MemoryAppender appender = new MemoryAppender(); | |
| 47 | + Logger logger = Logger.getLogger(TimestampGenerator.class); | |
| 48 | + Level originalLevel = logger.getLevel(); | |
| 49 | + logger.setLevel(Level.WARN); | |
| 50 | + logger.addAppender(appender); | |
| 62 | 51 | |
| 63 | 52 | try { |
| 64 | - Futures.allAsList(futures).get(); | |
| 65 | - } catch (ExecutionException e) { | |
| 66 | - Throwable cause = e.getCause(); | |
| 67 | - if (cause instanceof AssertionError) | |
| 68 | - throw (AssertionError) cause; | |
| 69 | - else | |
| 70 | - fail("Error in a test thread", cause); | |
| 71 | - } | |
| 72 | - | |
| 73 | - // Ensure that the 1000 microseconds for the mocked millisecond value have been generated | |
| 74 | - int i = 0; | |
| 75 | - for (Long timestamp : allTimestamps) { | |
| 76 | - Long expected = fixedTime * 1000 + i; | |
| 77 | - assertEquals(timestamp, expected); | |
| 78 | - i += 1; | |
| 53 | + // Generate 1000 timestamps shared among multiple threads | |
| 54 | + final int testThreadsCount = 2; | |
| 55 | + assertEquals(1000 % testThreadsCount, 0); | |
| 56 | + final SortedSet<Long> allTimestamps = new ConcurrentSkipListSet<Long>(); | |
| 57 | + ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(testThreadsCount)); | |
| 58 | + | |
| 59 | + List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount); | |
| 60 | + for (int i = 0; i < testThreadsCount; i++) { | |
| 61 | + futures.add(executor.submit( | |
| 62 | + new Runnable() { | |
| 63 | + @Override | |
| 64 | + public void run() { | |
| 65 | + for (int i = 0; i < 1000 / testThreadsCount; i++) | |
| 66 | + allTimestamps.add(generator.next()); | |
| 67 | + } | |
| 68 | + })); | |
| 69 | + } | |
| 70 | + executor.shutdown(); | |
| 71 | + executor.awaitTermination(1, TimeUnit.SECONDS); | |
| 72 | + | |
| 73 | + try { | |
| 74 | + Futures.allAsList(futures).get(); | |
| 75 | + } catch (ExecutionException e) { | |
| 76 | + Throwable cause = e.getCause(); | |
| 77 | + if (cause instanceof AssertionError) | |
| 78 | + throw (AssertionError) cause; | |
| 79 | + else | |
| 80 | + fail("Error in a test thread", cause); | |
| 81 | + } | |
| 82 | + | |
| 83 | + // Ensure that the 1000 microseconds for the mocked millisecond value have been generated | |
| 84 | + int i = 0; | |
| 85 | + for (Long timestamp : allTimestamps) { | |
| 86 | + Long expected = fixedTime + i; | |
| 87 | + assertEquals(timestamp, expected); | |
| 88 | + i += 1; | |
| 89 | + } | |
| 90 | + } finally { | |
| 91 | + logger.removeAppender(appender); | |
| 92 | + logger.setLevel(originalLevel); | |
| 79 | 93 | } |
| 80 | 94 | } |
| 81 | 95 | } |
modified driver-core/src/test/java/com/datastax/driver/core/MockClocks.java +2 −2
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | int calls; |
| 22 | 22 | |
| 23 | 23 | @Override |
| 24 | - public long currentTime() { | |
| 24 | + public long currentTimeMicros() { | |
| 25 | 25 | return arbitraryTimeStamp - calls++; |
| 26 | 26 | } |
| 27 | 27 | } |
| @@ -34,7 +34,7 @@ | ||
| 34 | 34 | } |
| 35 | 35 | |
| 36 | 36 | @Override |
| 37 | - public long currentTime() { | |
| 37 | + public long currentTimeMicros() { | |
| 38 | 38 | return fixedTime; |
| 39 | 39 | } |
| 40 | 40 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java +47 −10
| @@ -16,10 +16,9 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.google.common.collect.Lists; |
| 19 | -import com.google.common.util.concurrent.Futures; | |
| 20 | -import com.google.common.util.concurrent.ListenableFuture; | |
| 21 | -import com.google.common.util.concurrent.ListeningExecutorService; | |
| 22 | -import com.google.common.util.concurrent.MoreExecutors; | |
| 19 | +import com.google.common.util.concurrent.*; | |
| 20 | +import org.apache.log4j.Level; | |
| 21 | +import org.apache.log4j.Logger; | |
| 23 | 22 | import org.testng.annotations.Test; |
| 24 | 23 | |
| 25 | 24 | import java.util.List; |
| @@ -27,7 +26,9 @@ | ||
| 27 | 26 | import java.util.concurrent.Executors; |
| 28 | 27 | import java.util.concurrent.TimeUnit; |
| 29 | 28 | |
| 30 | -import static org.testng.Assert.*; | |
| 29 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 30 | +import static org.testng.Assert.assertEquals; | |
| 31 | +import static org.testng.Assert.fail; | |
| 31 | 32 | |
| 32 | 33 | public class ThreadLocalMonotonicTimestampGeneratorTest { |
| 33 | 34 | |
| @@ -51,7 +52,7 @@ | ||
| 51 | 52 | // Ensure that each thread gets the 1000 microseconds for the mocked millisecond value, |
| 52 | 53 | // in order |
| 53 | 54 | for (int i = 0; i < 1000; i++) |
| 54 | - assertEquals(generator.next(), fixedTime * 1000 + i); | |
| 55 | + assertEquals(generator.next(), fixedTime + i); | |
| 55 | 56 | } |
| 56 | 57 | })); |
| 57 | 58 | } |
| @@ -71,12 +72,48 @@ | ||
| 71 | 72 | |
| 72 | 73 | @Test(groups = "unit") |
| 73 | 74 | public void should_generate_incrementing_timestamps_on_clock_resync() { |
| 74 | - ThreadLocalMonotonicTimestampGenerator generator = new ThreadLocalMonotonicTimestampGenerator(); | |
| 75 | + ThreadLocalMonotonicTimestampGenerator generator = new ThreadLocalMonotonicTimestampGenerator(0, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); | |
| 75 | 76 | generator.clock = new MockClocks.BackInTimeClock(); |
| 76 | 77 | |
| 77 | - long beforeClockResync = generator.next(); | |
| 78 | - long afterClockResync = generator.next(); | |
| 78 | + MemoryAppender appender = new MemoryAppender(); | |
| 79 | + Logger logger = Logger.getLogger(TimestampGenerator.class); | |
| 80 | + Level originalLevel = logger.getLevel(); | |
| 81 | + logger.setLevel(Level.WARN); | |
| 82 | + logger.addAppender(appender); | |
| 83 | + String logFormat = "Clock skew detected: current tick (%d) was %d microseconds " + | |
| 84 | + "behind the last generated timestamp (%d), returned timestamps will be artificially incremented " + | |
| 85 | + "to guarantee monotonicity."; | |
| 79 | 86 | |
| 80 | - assertTrue(beforeClockResync < afterClockResync, "The generated timestamps are not increasing on block resync"); | |
| 87 | + try { | |
| 88 | + long start = generator.next(); | |
| 89 | + long previous = start; | |
| 90 | + long next = 0; | |
| 91 | + for (int i = 0; i < 1001; i++) { | |
| 92 | + next = generator.next(); | |
| 93 | + assertEquals(next, previous + 1); | |
| 94 | + previous = next; | |
| 95 | + } | |
| 96 | + | |
| 97 | + // Ensure log statement generated indicating clock skew, but only once. | |
| 98 | + assertEquals(next, start + 1001); | |
| 99 | + assertThat(appender.getNext()) | |
| 100 | + .containsOnlyOnce("Clock skew detected:") | |
| 101 | + .containsOnlyOnce(String.format(logFormat, start - 1, 1, start)); | |
| 102 | + | |
| 103 | + // Wait for a second to see if we get an additional clock skew message. | |
| 104 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 105 | + | |
| 106 | + next = generator.next(); | |
| 107 | + assertThat(next).isEqualTo(previous + 1); | |
| 108 | + // Clock has gone backwards 1002 us since we've had that many iterations. | |
| 109 | + // The difference should be 2003 (clock backwards 1002 + 1001 prior compute next calls). | |
| 110 | + // Current timestamp should match the previous one. | |
| 111 | + assertThat(appender.getNext()) | |
| 112 | + .containsOnlyOnce("Clock skew detected:") | |
| 113 | + .containsOnlyOnce(String.format(logFormat, start - 1002, 2003, previous)); | |
| 114 | + } finally { | |
| 115 | + logger.removeAppender(appender); | |
| 116 | + logger.setLevel(originalLevel); | |
| 117 | + } | |
| 81 | 118 | } |
| 82 | 119 | } |
modified manual/query_timestamps/README.md +56 −0
| @@ -60,6 +60,62 @@ | ||
| 60 | 60 | queries. |
| 61 | 61 | |
| 62 | 62 | |
| 63 | +The driver ships with two implementations of `TimestampGenerator`: | |
| 64 | + | |
| 65 | +1. [AtomicMonotonicTimestampGenerator][amtsg], which guarantess monotonicity of timestamps for all threads; | |
| 66 | +2. [ThreadLocalMonotonicTimestampGenerator][tlmtsg], which guarantees per-thread monotonicity of timestamps. | |
| 67 | + | |
| 68 | +There is less contention using `ThreadLocalMonotonicTimestampGenerator`, but beware | |
| 69 | +that there is a risk of timestamp collision with this generator when accessed by more than one | |
| 70 | +thread; only use it when threads are not in direct competition for timestamp ties (i.e., they are executing | |
| 71 | +independent statements). | |
| 72 | + | |
| 73 | +[amtsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.html | |
| 74 | +[tlmtsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.html | |
| 75 | + | |
| 76 | +#### Accuracy | |
| 77 | + | |
| 78 | +Both implementations strive to achieve microsecond resolution on a best-effort basis. | |
| 79 | +But in practice, the real accuracy of generated timestamps is largely dependent on the | |
| 80 | +granularity of the underlying operating system's clock. | |
| 81 | + | |
| 82 | +For most systems, this minimum granularity is millisecond, and | |
| 83 | +the sub-millisecond part of generated timestamps is simply a counter that gets incremented | |
| 84 | +until the next clock tick, as provided by `System.currentTimeMillis()`. | |
| 85 | + | |
| 86 | +On some systems, however, it is possible to have a better granularity by using a [JNR] | |
| 87 | +call to [gettimeofday]. This native call will be used when available, unless the system | |
| 88 | +property `com.datastax.driver.USE_NATIVE_CLOCK` is explicitly set to `false`. | |
| 89 | + | |
| 90 | +To check what's available on your system: | |
| 91 | + | |
| 92 | +* make sure your `Cluster` uses a `TimestampGenerator`; | |
| 93 | +* [configure your logging framework](../logging/) to use level `INFO` for the category | |
| 94 | + `com.datastax.driver.core.ClockFactory`; | |
| 95 | +* look for one of the following messages at startup: | |
| 96 | + | |
| 97 | + ``` | |
| 98 | + INFO com.datastax.driver.core.ClockFactory - Using java.lang.System clock to generate timestamps | |
| 99 | + INFO com.datastax.driver.core.ClockFactory - Using native clock to generate timestamps | |
| 100 | + ``` | |
| 101 | + | |
| 102 | +[gettimeofday]: http://man7.org/linux/man-pages/man2/settimeofday.2.html | |
| 103 | +[JNR]: https://github.com/jnr/jnr-ffi | |
| 104 | + | |
| 105 | +#### Monotonicity | |
| 106 | + | |
| 107 | +The aforementioned implementations also guarantee | |
| 108 | +that returned timestamps will always be monotonically increasing, even if multiple updates | |
| 109 | +happen under the same millisecond. | |
| 110 | + | |
| 111 | +Note that to guarantee such monotonicity, if more than one timestamp is generated | |
| 112 | +within the same microsecond, or in the event of a system clock skew, _both implementations might | |
| 113 | +return timestamps that drift out in the future_. | |
| 114 | + | |
| 115 | +When this happens, the built-in generators log a periodic warning message in the category | |
| 116 | +`com.datastax.driver.core.TimestampGenerator`. See their non-default constructors for ways to control the warning | |
| 117 | +interval. | |
| 118 | + | |
| 63 | 119 | ### Summary |
| 64 | 120 | |
| 65 | 121 | As shown in the previous sections, there are multiple ways to provide a |
modified pom.xml +5 −3
| @@ -15,13 +15,14 @@ | ||
| 15 | 15 | limitations under the License. |
| 16 | 16 | |
| 17 | 17 | --> |
| 18 | -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 18 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
| 19 | + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | 20 | <modelVersion>4.0.0</modelVersion> |
| 20 | 21 | <parent> |
| 21 | 22 | <groupId>org.sonatype.oss</groupId> |
| 22 | 23 | <artifactId>oss-parent</artifactId> |
| 23 | 24 | <version>7</version> |
| 24 | - <relativePath /> | |
| 25 | + <relativePath/> | |
| 25 | 26 | </parent> |
| 26 | 27 | |
| 27 | 28 | <groupId>com.datastax.cassandra</groupId> |
| @@ -61,6 +62,7 @@ | ||
| 61 | 62 | <joda.version>2.9.1</joda.version> |
| 62 | 63 | <jsr353-api.version>1.0</jsr353-api.version> |
| 63 | 64 | <jsr353-ri.version>1.0.4</jsr353-ri.version> |
| 65 | + <jnr-ffi.version>2.0.7</jnr-ffi.version> | |
| 64 | 66 | <!-- test dependency versions --> |
| 65 | 67 | <testng.version>6.8.8</testng.version> |
| 66 | 68 | <assertj.version>1.7.0</assertj.version> |
| @@ -71,7 +73,7 @@ | ||
| 71 | 73 | <ipprefix>127.0.1.</ipprefix> |
| 72 | 74 | <test.groups>unit</test.groups> |
| 73 | 75 | <!-- Set default javadoc.opts, overriden by profiles --> |
| 74 | - <javadoc.opts /> | |
| 76 | + <javadoc.opts/> | |
| 75 | 77 | </properties> |
| 76 | 78 | |
| 77 | 79 | <profiles> |