kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | cbe23d0de4cfee6d726db25d8f3697a23214c4165d069f899dd320e6adf5c369 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-03-09 22:07 +01:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-03-09 22:07 +01:00 |
| Parents | 15307c212676, b32166e873b8 |
19 files changed
modified changelog/README.md +1 −0
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | - [bug] JAVA-1070: The Mapper should not prepare queries synchronously. |
| 35 | 35 | - [new feature] JAVA-982: Introduce new method ConsistencyLevel.isSerial(). |
| 36 | 36 | - [bug] JAVA-764: Retry with the normal consistency level (not the serial one) when a write times out on the Paxos phase. |
| 37 | +- [bug] JAVA-727: Allow monotonic timestamp generators to drift in the future + use microsecond precision when possible. | |
| 37 | 38 | |
| 38 | 39 | Merged from 2.0 branch: |
| 39 | 40 |
modified driver-core/pom.xml +15 −2
| @@ -51,6 +51,12 @@ | ||
| 51 | 51 | <version>${metrics.version}</version> |
| 52 | 52 | </dependency> |
| 53 | 53 | |
| 54 | + <dependency> | |
| 55 | + <groupId>com.github.jnr</groupId> | |
| 56 | + <artifactId>jnr-ffi</artifactId> | |
| 57 | + <version>${jnr-ffi.version}</version> | |
| 58 | + </dependency> | |
| 59 | + | |
| 54 | 60 | <!-- Compression libraries for the protocol. --> |
| 55 | 61 | <!-- Each of them is only a mandatory runtime dependency if you want to use the compression it offers --> |
| 56 | 62 | |
| @@ -170,7 +176,9 @@ | ||
| 170 | 176 | <Bundle-SymbolicName>com.datastax.driver.core</Bundle-SymbolicName> |
| 171 | 177 | <Bundle-Version>${project.version}</Bundle-Version> |
| 172 | 178 | <_include>-osgi.bnd</_include> |
| 173 | - <Import-Package><![CDATA[com.google.common*;version="[14.0,19)",*]]></Import-Package> | |
| 179 | + <Import-Package> | |
| 180 | + <!-- JNR does not provide OSGi bundles, so exclude it; the driver can live without it --> | |
| 181 | + <![CDATA[com.google.common*;version="[14.0,19)",!jnr.*,*]]></Import-Package> | |
| 174 | 182 | </instructions> |
| 175 | 183 | <supportedProjectTypes> |
| 176 | 184 | <supportedProjectType>jar</supportedProjectType> |
| @@ -189,7 +197,12 @@ | ||
| 189 | 197 | <configuration> |
| 190 | 198 | <manifestLocation>${project.build.directory}/META-INF-shaded</manifestLocation> |
| 191 | 199 | <instructions> |
| 192 | - <Import-Package><![CDATA[com.google.common.*;version="[14.0,19)",!io.netty.*,javax.security.cert,*]]></Import-Package> | |
| 200 | + <Import-Package> | |
| 201 | + <!-- | |
| 202 | + JNR does not provide OSGi bundles, so exclude it; the driver can live without it | |
| 203 | + Explicitly import javax.security.cert because it's required by Netty, but Netty has been explicitly excluded | |
| 204 | + --> | |
| 205 | + <![CDATA[com.google.common.*;version="[14.0,19)",!jnr.*,!io.netty.*,javax.security.cert,*]]></Import-Package> | |
| 193 | 206 | <Private-Package>com.datastax.shaded.*</Private-Package> |
| 194 | 207 | </instructions> |
| 195 | 208 | </configuration> |
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 driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java +13 −5
| @@ -15,26 +15,34 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.osgi.api; |
| 17 | 17 | |
| 18 | -import java.util.Date; | |
| 18 | +import java.util.UUID; | |
| 19 | 19 | |
| 20 | 20 | public class MailboxMessage { |
| 21 | 21 | private String recipient; |
| 22 | - private Date date; | |
| 23 | 22 | private String sender; |
| 24 | 23 | private String body; |
| 24 | + private UUID date; | |
| 25 | 25 | |
| 26 | - public MailboxMessage(String recipient, Date date, String sender, String body) { | |
| 26 | + public MailboxMessage(String recipient, String sender, String body) { | |
| 27 | + this(recipient, sender, body, null); | |
| 28 | + } | |
| 29 | + | |
| 30 | + public MailboxMessage(String recipient, String sender, String body, UUID date) { | |
| 27 | 31 | this.recipient = recipient; |
| 28 | - this.date = date; | |
| 29 | 32 | this.sender = sender; |
| 30 | 33 | this.body = body; |
| 34 | + this.date = date; | |
| 31 | 35 | } |
| 32 | 36 | |
| 33 | 37 | public String getRecipient() { |
| 34 | 38 | return recipient; |
| 35 | 39 | } |
| 36 | 40 | |
| 37 | - public Date getDate() { | |
| 41 | + public void setDate(UUID date) { | |
| 42 | + this.date = date; | |
| 43 | + } | |
| 44 | + | |
| 45 | + public UUID getDate() { | |
| 38 | 46 | return date; |
| 39 | 47 | } |
| 40 | 48 |
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +4 −1
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.osgi.impl; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.AtomicMonotonicTimestampGenerator; | |
| 18 | 19 | import com.datastax.driver.core.Cluster; |
| 19 | 20 | import com.datastax.driver.core.Session; |
| 20 | 21 | import com.datastax.driver.osgi.api.MailboxService; |
| @@ -40,7 +41,9 @@ | ||
| 40 | 41 | keyspace = "mailbox"; |
| 41 | 42 | } |
| 42 | 43 | |
| 43 | - cluster = Cluster.builder().addContactPoints(contactPoints).build(); | |
| 44 | + cluster = Cluster.builder().addContactPoints(contactPoints) | |
| 45 | + .withTimestampGenerator(new AtomicMonotonicTimestampGenerator()) | |
| 46 | + .build(); | |
| 44 | 47 | Session session = cluster.connect(); |
| 45 | 48 | |
| 46 | 49 | MailboxImpl mailbox = new MailboxImpl(session, keyspace); |
modified driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +3 −6
| @@ -24,7 +24,6 @@ | ||
| 24 | 24 | |
| 25 | 25 | import java.util.ArrayList; |
| 26 | 26 | import java.util.Collection; |
| 27 | -import java.util.Date; | |
| 28 | 27 | import java.util.UUID; |
| 29 | 28 | |
| 30 | 29 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| @@ -94,11 +93,10 @@ | ||
| 94 | 93 | |
| 95 | 94 | Collection<MailboxMessage> messages = new ArrayList<MailboxMessage>(); |
| 96 | 95 | for (Row input : result) { |
| 97 | - Date date = new Date(UUIDs.unixTimestamp(input.getUUID("time"))); | |
| 98 | 96 | messages.add(new MailboxMessage(input.getString("recipient"), |
| 99 | - date, | |
| 100 | 97 | input.getString("sender"), |
| 101 | - input.getString("body"))); | |
| 98 | + input.getString("body"), | |
| 99 | + input.getUUID("time"))); | |
| 102 | 100 | } |
| 103 | 101 | return messages; |
| 104 | 102 | } catch (Exception e) { |
| @@ -109,8 +107,7 @@ | ||
| 109 | 107 | @Override |
| 110 | 108 | public UUID sendMessage(MailboxMessage message) throws MailboxException { |
| 111 | 109 | try { |
| 112 | - UUID time = UUIDs.startOf(message.getDate().getTime()); | |
| 113 | - | |
| 110 | + UUID time = UUIDs.timeBased(); | |
| 114 | 111 | BoundStatement statement = new BoundStatement(insertStatement); |
| 115 | 112 | statement.setString(0, message.getRecipient()); |
| 116 | 113 | statement.setUUID(1, time); |
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +4 −3
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | import javax.inject.Inject; |
| 32 | 32 | import java.util.ArrayList; |
| 33 | 33 | import java.util.Collection; |
| 34 | -import java.util.GregorianCalendar; | |
| 34 | +import java.util.UUID; | |
| 35 | 35 | |
| 36 | 36 | import static com.datastax.driver.osgi.VersionProvider.projectVersion; |
| 37 | 37 | import static org.ops4j.pax.exam.CoreOptions.*; |
| @@ -178,9 +178,10 @@ | ||
| 178 | 178 | try { |
| 179 | 179 | Collection<MailboxMessage> inMessages = new ArrayList<MailboxMessage>(); |
| 180 | 180 | for (int i = 0; i < 30; i++) { |
| 181 | - MailboxMessage message = new MailboxMessage(recipient, new GregorianCalendar(2015, 1, i).getTime(), recipient, "" + i); | |
| 181 | + MailboxMessage message = new MailboxMessage(recipient, recipient, "" + i); | |
| 182 | + UUID time = service.sendMessage(message); | |
| 183 | + message.setDate(time); | |
| 182 | 184 | inMessages.add(message); |
| 183 | - service.sendMessage(message); | |
| 184 | 185 | } |
| 185 | 186 | |
| 186 | 187 | Collection<MailboxMessage> messages = service.getMessages(recipient); |
modified manual/query_timestamps/README.md +56 −0
| @@ -59,6 +59,62 @@ | ||
| 59 | 59 | |
| 60 | 60 | [tsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/TimestampGenerator.html |
| 61 | 61 | |
| 62 | +The driver ships with two implementations of `TimestampGenerator`: | |
| 63 | + | |
| 64 | +1. [AtomicMonotonicTimestampGenerator][amtsg], which guarantess monotonicity of timestamps for all threads; | |
| 65 | +2. [ThreadLocalMonotonicTimestampGenerator][tlmtsg], which guarantees per-thread monotonicity of timestamps. | |
| 66 | + | |
| 67 | +There is less contention using `ThreadLocalMonotonicTimestampGenerator`, but beware | |
| 68 | +that there is a risk of timestamp collision with this generator when accessed by more than one | |
| 69 | +thread; only use it when threads are not in direct competition for timestamp ties (i.e., they are executing | |
| 70 | +independent statements). | |
| 71 | + | |
| 72 | +[amtsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.html | |
| 73 | +[tlmtsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.html | |
| 74 | + | |
| 75 | +#### Accuracy | |
| 76 | + | |
| 77 | +Both implementations strive to achieve microsecond resolution on a best-effort basis. | |
| 78 | +But in practice, the real accuracy of generated timestamps is largely dependent on the | |
| 79 | +granularity of the underlying operating system's clock. | |
| 80 | + | |
| 81 | +For most systems, this minimum granularity is millisecond, and | |
| 82 | +the sub-millisecond part of generated timestamps is simply a counter that gets incremented | |
| 83 | +until the next clock tick, as provided by `System.currentTimeMillis()`. | |
| 84 | + | |
| 85 | +On some systems, however, it is possible to have a better granularity by using a [JNR] | |
| 86 | +call to [gettimeofday]. This native call will be used when available, unless the system | |
| 87 | +property `com.datastax.driver.USE_NATIVE_CLOCK` is explicitly set to `false`. | |
| 88 | + | |
| 89 | +To check what's available on your system: | |
| 90 | + | |
| 91 | +* make sure your `Cluster` uses a `TimestampGenerator`; | |
| 92 | +* [configure your logging framework](../logging/) to use level `INFO` for the category | |
| 93 | + `com.datastax.driver.core.ClockFactory`; | |
| 94 | +* look for one of the following messages at startup: | |
| 95 | + | |
| 96 | + ``` | |
| 97 | + INFO com.datastax.driver.core.ClockFactory - Using java.lang.System clock to generate timestamps | |
| 98 | + INFO com.datastax.driver.core.ClockFactory - Using native clock to generate timestamps | |
| 99 | + ``` | |
| 100 | + | |
| 101 | +[gettimeofday]: http://man7.org/linux/man-pages/man2/settimeofday.2.html | |
| 102 | +[JNR]: https://github.com/jnr/jnr-ffi | |
| 103 | + | |
| 104 | +#### Monotonicity | |
| 105 | + | |
| 106 | +The aforementioned implementations also guarantee | |
| 107 | +that returned timestamps will always be monotonically increasing, even if multiple updates | |
| 108 | +happen under the same millisecond. | |
| 109 | + | |
| 110 | +Note that to guarantee such monotonicity, if more than one timestamp is generated | |
| 111 | +within the same microsecond, or in the event of a system clock skew, _both implementations might | |
| 112 | +return timestamps that drift out in the future_. | |
| 113 | + | |
| 114 | +When this happens, the built-in generators log a periodic warning message in the category | |
| 115 | +`com.datastax.driver.core.TimestampGenerator`. See their non-default constructors for ways to control the warning | |
| 116 | +interval. | |
| 117 | + | |
| 62 | 118 | ### Summary |
| 63 | 119 | |
| 64 | 120 | As shown in the previous sections, there are multiple ways to provide a |
modified pom.xml +1 −0
| @@ -56,6 +56,7 @@ | ||
| 56 | 56 | <snappy.version>1.0.5</snappy.version> |
| 57 | 57 | <lz4.version>1.2.0</lz4.version> |
| 58 | 58 | <hdr.version>2.1.4</hdr.version> |
| 59 | + <jnr-ffi.version>2.0.7</jnr-ffi.version> | |
| 59 | 60 | <!-- test dependency versions --> |
| 60 | 61 | <testng.version>6.8.8</testng.version> |
| 61 | 62 | <assertj.version>1.7.0</assertj.version> |