From 84a9581c7f86c7f2f51f08a2c38c3864b078313b Mon Sep 17 00:00:00 2001 From: Rob Austin Date: Wed, 26 Nov 2014 16:24:57 +0000 Subject: [PATCH] HCOLL-218 ReplicatedChronicleMapTest appears to use too much resources - I've looked at other tests as well and have attempted to ensure that close is called on every test, also prompting the GC to run after each test. --- .../chronicle/hash/ChronicleHashBuilder.java | 358 +++++----- .../chronicle/set/ChronicleSetBuilder.java | 97 +-- .../chronicle/map/CHMTestIterator1.java | 27 +- .../chronicle/map/ChannelReplicationTest.java | 1 + .../map/ConstantSizeBySampleTest.java | 39 +- .../chronicle/map/DemoChronicleMapTest.java | 91 +-- ...tListenerTestWithTCPSocketReplication.java | 1 + .../chronicle/map/IntValueMapTest.java | 24 +- .../openhft/chronicle/map/Issue42Test.java | 22 +- .../map/PostChannelCreationTest.java | 1 + .../chronicle/map/SingleMapChannelTest.java | 1 + .../chronicle/map/StatelessClientTest.java | 2 + .../TCPSocketReplication3VoidValueTest.java | 1 + ...cketReplication3wayPutReturnsNullTest.java | 1 + .../map/TCPSocketReplication4WayMapTest.java | 1 + .../TCPSocketReplicationBootStrapTest.java | 1 + .../map/TCPSocketReplicationIntValueTest.java | 2 + .../map/TCPSocketReplicationNativeTest.java | 1 + ...CPSocketReplicationPostConnectionTest.java | 1 + .../map/TCPSocketReplicationTest.java | 1 + .../chronicle/map/TestBooleanValues.java | 9 +- .../map/TimeBasedReplicationTest.java | 293 ++++---- .../map/TwoMapOnDifferentServersTest.java | 1 + .../map/UDPSocketReplicationTest.java | 6 +- .../map/example/DistributedSequenceMain.java | 19 +- .../fromdocs/StringEncodingExamplesTest.java | 28 +- .../chronicle/map/jrs166/JSR166TestCase.java | 1 + .../map/jrs166/map/ChronicleMapTest.java | 634 ++++++++---------- .../set/ChronicleSetBuilderTest.java | 16 +- .../chronicle/{map => set}/Issue3Test.java | 20 +- .../SetForTCPSocketReplication3wayTest.java | 1 + 31 files changed, 844 insertions(+), 857 deletions(-) rename src/test/java/net/openhft/chronicle/{map => set}/Issue3Test.java (68%) diff --git a/src/main/java/net/openhft/chronicle/hash/ChronicleHashBuilder.java b/src/main/java/net/openhft/chronicle/hash/ChronicleHashBuilder.java index c84f2cf82..ced83ebca 100755 --- a/src/main/java/net/openhft/chronicle/hash/ChronicleHashBuilder.java +++ b/src/main/java/net/openhft/chronicle/hash/ChronicleHashBuilder.java @@ -45,32 +45,36 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** - * This interface defines the meaning of configurations, common to {@link net.openhft.chronicle.map.OnHeapUpdatableChronicleMapBuilder} - * and {@link ChronicleSetBuilder}, i. e. Chronicle hash container configurations. + * This interface defines the meaning of configurations, common to {@link + * net.openhft.chronicle.map.OnHeapUpdatableChronicleMapBuilder} and {@link ChronicleSetBuilder}, i. + * e. Chronicle hash container configurations. * - *

{@code ChronicleHashBuilder} is mutable. Configuration methods mutate the builder and return the - * builder itself back to support chaining pattern, rather than the builder copies with the corresponding - * configuration changed. To make an independent configuration, {@linkplain #clone} the builder. + *

{@code ChronicleHashBuilder} is mutable. Configuration methods mutate the builder and return + * the builder itself back to support chaining pattern, rather than the builder copies with + * the corresponding configuration changed. To make an independent configuration, {@linkplain + * #clone} the builder. * * @param the type of keys in hash containers, created by this builder - * @param the container type, created by this builder, i. e. {@link ChronicleMap} or {@link ChronicleSet} - * @param the concrete builder type, i. e. {@link net.openhft.chronicle.map.ChronicleMapOnHeapUpdatableBuilder} + * @param the container type, created by this builder, i. e. {@link ChronicleMap} or {@link + * ChronicleSet} + * @param the concrete builder type, i. e. {@link net.openhft.chronicle.map.ChronicleMapBuilder} * or {@link ChronicleSetBuilder} */ public interface ChronicleHashBuilder> extends Cloneable { /** - * Clones this builder. Useful for configuration persisting, because {@code ChronicleHashBuilder}s are - * mutable and changed on each configuration method call. Original and cloned builders are independent. + * Clones this builder. Useful for configuration persisting, because {@code + * ChronicleHashBuilder}s are mutable and changed on each configuration method call. Original + * and cloned builders are independent. * * @return a new clone of this builder */ B clone(); /** - * Set minimum number of segments in hash containers, constructed by this builder. See concurrencyLevel in - * {@link ConcurrentHashMap}. + * Set minimum number of segments in hash containers, constructed by this builder. See + * concurrencyLevel in {@link ConcurrentHashMap}. * * @param minSegments the minimum number of segments in containers, constructed by this builder * @return this builder object back @@ -78,13 +82,14 @@ public interface ChronicleHashBuilderIf key size varies moderately, specify the size higher than average, but lower than the maximum - * possible, to minimize average memory overuse. If key size varies in a wide range, it's better to use - * {@linkplain #entrySize(int) entry size} in "chunk" mode and configure it directly. + *

If key size varies moderately, specify the size higher than average, but lower than the + * maximum possible, to minimize average memory overuse. If key size varies in a wide range, + * it's better to use {@linkplain #entrySize(int) entry size} in "chunk" mode and configure it + * directly. * * @param keySize number of bytes, taken by serialized form of keys * @return this builder back @@ -94,15 +99,15 @@ public interface ChronicleHashBuilderIf keys are of boxed primitive type or {@link Byteable} subclass, i. e. if key size is known - * statically, it is automatically accounted and this method shouldn't be called. + *

If keys are of boxed primitive type or {@link Byteable} subclass, i. e. if key size is + * known statically, it is automatically accounted and this method shouldn't be called. * - *

If key size varies, method {@link #keySize(int)} or {@link #entrySize(int)} should be called instead - * of this one. + *

If key size varies, method {@link #keySize(int)} or {@link #entrySize(int)} should be + * called instead of this one. * * @param sampleKey the sample key * @return this builder back @@ -111,42 +116,44 @@ public interface ChronicleHashBuilder{@link ChronicleMap} and {@link ChronicleSet} store their data off-heap, so it is required to - * serialize key (and values, in {@code ChronicleMap} case) (unless they are direct {@link Byteable} - * instances). Serialized key bytes (+ serialized value bytes, in {@code ChronicleMap} case) + some - * metadata bytes comprise "entry space", which {@code ChronicleMap} or {@code ChronicleSet} should - * allocate. So entry size is a minimum allocation portion in the hash containers, created by this - * builder. E. g. if entry size is 100, the created container could only allocate 100, 200, 300... bytes - * for an entry. If say 150 bytes of entry space are required by the entry, 200 bytes will be allocated, - * 150 used and 50 wasted. To minimize memory overuse and improve speed, you should pay decent attention - * to this configuration. + *

{@link ChronicleMap} and {@link ChronicleSet} store their data off-heap, so it is required + * to serialize key (and values, in {@code ChronicleMap} case) (unless they are direct {@link + * Byteable} instances). Serialized key bytes (+ serialized value bytes, in {@code ChronicleMap} + * case) + some metadata bytes comprise "entry space", which {@code ChronicleMap} or {@code + * ChronicleSet} should allocate. So entry size is a minimum allocation portion in the + * hash containers, created by this builder. E. g. if entry size is 100, the created container + * could only allocate 100, 200, 300... bytes for an entry. If say 150 bytes of entry space are + * required by the entry, 200 bytes will be allocated, 150 used and 50 wasted. To minimize + * memory overuse and improve speed, you should pay decent attention to this configuration. * - *

There are three major patterns of this configuration usage:

  1. Key (and value, in {@code - * ChronicleMap} case) sizes are constant. Configure them via {@link #constantKeySizeBySample(Object)} and - * {@link net.openhft.chronicle.map.OnHeapUpdatableChronicleMapBuilder#constantValueSizeBySample(Object)} - * methods, and you will experience no memory waste at all.
  2. Key (and/or value size, in {@code - * ChronicleMap} case) varies moderately. Specify them using corresponding methods, or specify entry size - * directly by calling this method, by sizes somewhere between average and maximum possible. The idea is - * to have most (90% or more) entries to fit a single "entry size" with moderate memory waste (10-20% on - * average), rest 10% or less of entries should take 2 "entry sizes", thus with ~50% memory overuse.
  3. - *
  4. Key (and/or value size, in {@code ChronicleMap} case) varies in a wide range. Then it's best to use - * entry size configuration in chunk mode. Specify entry size so that most entries should take from - * 5 to several dozens of "chunks". With this approach, average memory waste should be very low. + *

    There are three major patterns of this configuration usage:

    1. Key (and value, in + * {@code ChronicleMap} case) sizes are constant. Configure them via {@link + * #constantKeySizeBySample(Object)} and {@link net.openhft.chronicle.map.OnHeapUpdatableChronicleMapBuilder#constantValueSizeBySample(Object)} + * methods, and you will experience no memory waste at all.
    2. Key (and/or value size, in + * {@code ChronicleMap} case) varies moderately. Specify them using corresponding methods, or + * specify entry size directly by calling this method, by sizes somewhere between average and + * maximum possible. The idea is to have most (90% or more) entries to fit a single "entry size" + * with moderate memory waste (10-20% on average), rest 10% or less of entries should take 2 + * "entry sizes", thus with ~50% memory overuse.
    3. Key (and/or value size, in {@code + * ChronicleMap} case) varies in a wide range. Then it's best to use entry size configuration in + * chunk mode. Specify entry size so that most entries should take from 5 to several + * dozens of "chunks". With this approach, average memory waste should be very low. * - *

      However, remember that

      • Operations with entries that span several "entry sizes" are a bit - * slower, than entries which take a single "entry size". That is why "chunk" approach is not recommended, - * when key (and/or value size) varies moderately.
      • The maximum number of chunks could be taken by - * an entry is 64. {@link IllegalArgumentException} is thrown on attempt to insert too large entry, - * compared to the configured or computed entry size.
      • The number of "entries" {@linkplain - * #entries(long) in the whole map} and {@linkplain #actualEntriesPerSegment(long) per segment} is - * actually the number "chunks".
      + *

      However, remember that

      • Operations with entries that span several "entry sizes" + * are a bit slower, than entries which take a single "entry size". That is why "chunk" approach + * is not recommended, when key (and/or value size) varies moderately.
      • The maximum + * number of chunks could be taken by an entry is 64. {@link IllegalArgumentException} is thrown + * on attempt to insert too large entry, compared to the configured or computed entry size.
      • + *
      • The number of "entries" {@linkplain #entries(long) in the whole map} and {@linkplain + * #actualEntriesPerSegment(long) per segment} is actually the number "chunks".
      * - *

      Example: if values in your {@code ChronicleMap} are adjacency lists of some social graph, where - * nodes are represented as {@code long} ids, and adjacency lists are serialized in efficient manner, for - * example as {@code long[]} arrays. Typical number of connections is 100-300, maximum is 3000. In this - * case entry size of + *

      Example: if values in your {@code ChronicleMap} are adjacency lists of some social graph, + * where nodes are represented as {@code long} ids, and adjacency lists are serialized in + * efficient manner, for example as {@code long[]} arrays. Typical number of connections is + * 100-300, maximum is 3000. In this case entry size of * 50 * (8 bytes for each id) = 400 bytes would be a good choice:

      {@code
            * Map socialGraph = ChronicleMapOnHeapUpdatableBuilder
            *     .of(Long.class, long[].class)
      @@ -155,8 +162,9 @@ public interface ChronicleHashBuilder
      -     * It is minimum possible (because 3000 friends / 50 friends = 60 is close to 64 "max chunks by single
      -     * entry" limit, and ensures moderate average memory overuse (not more than 20%). 
    + * It is minimum possible (because 3000 friends / 50 friends = 60 is close to 64 "max chunks by + * single entry" limit, and ensures moderate average memory overuse (not more than 20%).
  5. + *
* * @param entrySize the "chunk size" in bytes * @return this builder back @@ -165,29 +173,33 @@ public interface ChronicleHashBuilder
  • If key size (and value size, in {@code ChronicleMap} case) is constant, this number is equal - * to the maximum number of entries (because each entry takes exactly one "entry size" memory unit).
  • - *
  • If key (and/or value, in {@code ChronicleMap} case) size varies moderately, you should pass to this - * method the maximum number of entries + 5-25%, depending on your data properties and configured - * {@linkplain #keySize(int) key}/{@linkplain net.openhft.chronicle.map.OnHeapUpdatableChronicleMapBuilder#valueSize(int) - * value}/{@linkplain #entrySize(int) entry} sizes.
  • If your data size varies in a wide range, - * pass the maximum number of entries multiplied by average data size and divided by the configured "entry - * size" (i. e. chunk size). See an example in the documentation to {@link #entrySize(int)} method.
  • - * + *
    1. If key size (and value size, in {@code ChronicleMap} case) is constant, this number + * is equal to the maximum number of entries (because each entry takes exactly one "entry size" + * memory unit).
    2. If key (and/or value, in {@code ChronicleMap} case) size varies + * moderately, you should pass to this method the maximum number of entries + 5-25%, depending + * on your data properties and configured {@linkplain #keySize(int) key}/{@linkplain + * net.openhft.chronicle.map.OnHeapUpdatableChronicleMapBuilder#valueSize(int) + * value}/{@linkplain #entrySize(int) entry} sizes.
    3. If your data size varies in a wide + * range, pass the maximum number of entries multiplied by average data size and divided by the + * configured "entry size" (i. e. chunk size). See an example in the documentation to {@link + * #entrySize(int)} method.
    * - *

    You shouldn't put additional margin over the number, computed according the rules above. This bad - * practice was popularized by {@link HashMap#HashMap(int)} and {@link HashSet#HashSet(int)} constructors, - * which accept "capacity", that should be multiplied by "load factor" to obtain actual maximum expected - * number of entries. {@code ChronicleMap} and {@code ChronicleSet} don't have a notion of load factor. + *

    You shouldn't put additional margin over the number, computed according the rules above. + * This bad practice was popularized by {@link HashMap#HashMap(int)} and {@link + * HashSet#HashSet(int)} constructors, which accept "capacity", that should be multiplied by + * "load factor" to obtain actual maximum expected number of entries. {@code ChronicleMap} and + * {@code ChronicleSet} don't have a notion of load factor. * *

    Default value is 2^20 (~ 1 million). * - * @param entries maximum size of the created maps, in memory allocation units, so-called "entry size" + * @param entries maximum size of the created maps, in memory allocation units, so-called "entry + * size" * @return this builder back * @see #entrySize(int) */ @@ -198,17 +210,18 @@ public interface ChronicleHashBuilderDefault lock time out is 2 seconds. * - * @param lockTimeOut new lock timeout for segments of containers created by this builder, in the given - * time units + * @param lockTimeOut new lock timeout for segments of containers created by this builder, in + * the given time units * @param unit time unit of the given lock timeout * @return this builder back */ @@ -219,8 +232,8 @@ public interface ChronicleHashBuilderDefault time provider is {@link TimeProvider#SYSTEM}. * @@ -231,15 +244,17 @@ public interface ChronicleHashBuilderDefault {@code BytesMarshallerFactory} is an instance of {@link VanillaBytesMarshallerFactory}. This - * is a convenience configuration method, it has no effect on the resulting hash containers, if - * {@linkplain #keyMarshaller(BytesMarshaller) custom data marshallers} are configured, data types extends - * one of specific serialization interfaces, recognized by this builder (e. g. {@code Externalizable} or - * {@code BytesMarshallable}), or {@code ObjectSerializer} is configured. + *

    Default {@code BytesMarshallerFactory} is an instance of {@link + * VanillaBytesMarshallerFactory}. This is a convenience configuration method, it has no effect + * on the resulting hash containers, if {@linkplain #keyMarshaller(BytesMarshaller) custom data + * marshallers} are configured, data types extends one of specific serialization interfaces, + * recognized by this builder (e. g. {@code Externalizable} or {@code BytesMarshallable}), or + * {@code ObjectSerializer} is configured. * * @param bytesMarshallerFactory the marshaller factory to be used with the default {@code * ObjectSerializer}, i. e. {@code BytesMarshallableSerializer} @@ -249,18 +264,18 @@ public interface ChronicleHashBuilderDefault serializer is {@link BytesMarshallableSerializer}, configured with the specified or default - * {@link #bytesMarshallerFactory(BytesMarshallerFactory) BytesMarshallerFactory}. + *

    Default serializer is {@link BytesMarshallableSerializer}, configured with the specified + * or default {@link #bytesMarshallerFactory(BytesMarshallerFactory) BytesMarshallerFactory}. * - * @param objectSerializer the serializer used to serialize loosely typed or nullable data if custom - * marshaller is not configured + * @param objectSerializer the serializer used to serialize loosely typed or nullable data if + * custom marshaller is not configured * @return this builder back * @see #bytesMarshallerFactory(BytesMarshallerFactory) * @see #keyMarshaller(BytesMarshaller) @@ -268,8 +283,8 @@ public interface ChronicleHashBuilderthe + * Configures the {@code BytesMarshaller} used to serialize/deserialize keys to/from off-heap + * memory in hash containers, created by this builder. See the * section about serialization in ChronicleMap manual for more information. * * @param keyMarshaller the marshaller used to serialize keys @@ -280,15 +295,15 @@ public interface ChronicleHashBuilder keyMarshaller); /** - * Configures the marshallers, used to serialize/deserialize keys to/from off-heap memory in hash - * containers, created by this builder. See the + * Configures the marshallers, used to serialize/deserialize keys to/from off-heap memory in + * hash containers, created by this builder. See the * section about serialization in ChronicleMap manual for more information. * - *

    Configuring marshalling this way results to a little bit more compact in-memory layout of the map, - * comparing to a single interface configuration: {@link #keyMarshaller(BytesMarshaller)}. + *

    Configuring marshalling this way results to a little bit more compact in-memory layout of + * the map, comparing to a single interface configuration: {@link #keyMarshaller(BytesMarshaller)}. * - *

    Passing {@link BytesInterop} (which is a subinterface of {@link BytesWriter}) as the first argument - * is supported, and even more advantageous from performance perspective. + *

    Passing {@link BytesInterop} (which is a subinterface of {@link BytesWriter}) as the first + * argument is supported, and even more advantageous from performance perspective. * * @param keyWriter the new key object → {@link Bytes} writer (interop) strategy * @param keyReader the new {@link Bytes} → key object reader strategy @@ -298,53 +313,57 @@ public interface ChronicleHashBuilder keyWriter, @NotNull BytesReader keyReader); /** - * Configures the marshaller used to serialize actual key sizes to off-heap memory in hash containers, - * created by this builder. + * Configures the marshaller used to serialize actual key sizes to off-heap memory in hash + * containers, created by this builder. * - *

    Default key size marshaller is so-called {@linkplain SizeMarshallers#stopBit() stop bit encoding - * marshalling}. If {@linkplain #constantKeySizeBySample(Object) constant key size} is configured, or - * defaulted if the key type is always constant and {@code ChronicleHashBuilder} implementation knows - * about it, this configuration takes no effect, because a special {@link SizeMarshaller} implementation, - * which doesn't actually do any marshalling, and just returns the known constant size on {@link - * SizeMarshaller#readSize(Bytes)} calls, is used instead of any {@code SizeMarshaller} configured using - * this method. + *

    Default key size marshaller is so-called {@linkplain SizeMarshallers#stopBit() stop bit + * encoding marshalling}. If {@linkplain #constantKeySizeBySample(Object) constant key size} is + * configured, or defaulted if the key type is always constant and {@code ChronicleHashBuilder} + * implementation knows about it, this configuration takes no effect, because a special {@link + * SizeMarshaller} implementation, which doesn't actually do any marshalling, and just returns + * the known constant size on {@link SizeMarshaller#readSize(Bytes)} calls, is used instead of + * any {@code SizeMarshaller} configured using this method. * - * @param keySizeMarshaller the new marshaller, used to serialize actual key sizes to off-heap memory + * @param keySizeMarshaller the new marshaller, used to serialize actual key sizes to off-heap + * memory * @return this builder back */ B keySizeMarshaller(@NotNull SizeMarshaller keySizeMarshaller); /** - * Configures factory which is used to create a new key instance, if key class is either {@link Byteable}, - * {@link BytesMarshallable} or {@link Externalizable} subclass in maps, created by this builder. If - * {@linkplain #keyMarshaller(BytesMarshaller) custom key marshaller} is configured, this configuration is - * unused, because it is incapsulated in {@link BytesMarshaller#read(Bytes)} method (without provided - * instance to read the data into), i. e. it's is the user-side responsibility. + * Configures factory which is used to create a new key instance, if key class is either {@link + * Byteable}, {@link BytesMarshallable} or {@link Externalizable} subclass in maps, created by + * this builder. If {@linkplain #keyMarshaller(BytesMarshaller) custom key marshaller} is + * configured, this configuration is unused, because it is incapsulated in {@link + * BytesMarshaller#read(Bytes)} method (without provided instance to read the data into), i. e. + * it's is the user-side responsibility. * - *

    Default key deserialization factory is {@link NewInstanceObjectFactory}, which creates a new key - * instance using {@link Class#newInstance()} default constructor. You could provide an {@link - * AllocateInstanceObjectFactory}, which uses {@code Unsafe.allocateInstance(Class)} (you might want to do - * this for better performance or if you don't want to initialize fields), or a factory which calls a key - * class constructor with some arguments, or a factory which internally delegates to instance pool or - * {@link ThreadLocal}, to reduce allocations. + *

    Default key deserialization factory is {@link NewInstanceObjectFactory}, which creates a + * new key instance using {@link Class#newInstance()} default constructor. You could provide an + * {@link AllocateInstanceObjectFactory}, which uses {@code Unsafe.allocateInstance(Class)} (you + * might want to do this for better performance or if you don't want to initialize fields), or a + * factory which calls a key class constructor with some arguments, or a factory which + * internally delegates to instance pool or {@link ThreadLocal}, to reduce allocations. * - * @param keyDeserializationFactory the key factory used to produce instances to deserialize data in + * @param keyDeserializationFactory the key factory used to produce instances to deserialize + * data in * @return this builder back - * @throws IllegalStateException if custom key marshaller is specified or key class is not either {@code - * Byteable}, {@code BytesMarshallable} or {@code Externalizable} + * @throws IllegalStateException if custom key marshaller is specified or key class is not + * either {@code Byteable}, {@code BytesMarshallable} or {@code + * Externalizable} */ B keyDeserializationFactory(@NotNull ObjectFactory keyDeserializationFactory); /** - * Specifies that key objects, queried with the hash containers, created by this builder, are inherently - * immutable. Keys in {@link ChronicleMap} or {@link ChronicleSet} are not required to be immutable, as in - * ordinary {@link Map} or {@link Set} implementations, because they are serialized off-heap. However, - * {@code ChronicleMap} and {@code ChronicleSet} implementations can benefit from the knowledge that keys - * are not mutated between queries. + * Specifies that key objects, queried with the hash containers, created by this builder, are + * inherently immutable. Keys in {@link ChronicleMap} or {@link ChronicleSet} are not required + * to be immutable, as in ordinary {@link Map} or {@link Set} implementations, because they are + * serialized off-heap. However, {@code ChronicleMap} and {@code ChronicleSet} implementations + * can benefit from the knowledge that keys are not mutated between queries. * - *

    By default, {@code ChronicleHashBuilder}s detects immutability automatically only for very few - * standard JDK types (for example, for {@link String}), it is not recommended to rely on {@code - * ChronicleHashBuilder} to be smart enough about this. + *

    By default, {@code ChronicleHashBuilder}s detects immutability automatically only for very + * few standard JDK types (for example, for {@link String}), it is not recommended to rely on + * {@code ChronicleHashBuilder} to be smart enough about this. * * @return this builder back */ @@ -352,13 +371,14 @@ public interface ChronicleHashBuilder the section about replication in - * ChronicleMap manual for more information. + * href="https://github.com/OpenHFT/Chronicle-Map#tcp--udp-replication"> the section about + * replication in ChronicleMap manual for more information. * *

    By default, hash containers, created by this builder doesn't replicate their data. * - *

    This method call overrides all previous replication configurations of this builder, made either by - * this method or {@link #replication(byte, TcpTransportAndNetworkConfig)} shortcut method. + *

    This method call overrides all previous replication configurations of this builder, made + * either by this method or {@link #replication(byte, TcpTransportAndNetworkConfig)} shortcut + * method. * * @param replication the replication config * @return this builder back @@ -370,7 +390,8 @@ public interface ChronicleHashBuilder instance(); /** - * Creates a new hash container, storing it's data in off-heap memory, not mapped to any file. On {@link - * ChronicleHash#close()} called on the returned container, or after the container object is collected - * during GC, or on JVM shutdown the off-heap memory used by the returned container is freed. + * Creates a new hash container, storing it's data in off-heap memory, not mapped to any file. + * On {@link ChronicleHash#close()} called on the returned container, or after the container + * object is collected during GC, or on JVM shutdown the off-heap memory used by the returned + * container is freed. * *

    This method is a shortcut for {@code instance().create()}. * * @return a new off-heap hash container - * @throws IOException if any IO error relates to off-heap memory allocation, or establishing replication - * connections, occurs + * @throws IOException if any IO error relates to off-heap memory allocation, or establishing + * replication connections, occurs * @see #createPersistedTo(File) * @see #instance() */ C create() throws IOException; /** - * Opens a hash container residing the specified file, or creates a new one if the file not yet exists and - * maps its off-heap memory to the file. All changes to the map are persisted to disk (this is an - * operating system guarantee) independently from JVM process lifecycle. + * Opens a hash container residing the specified file, or creates a new one if the file not yet + * exists and maps its off-heap memory to the file. All changes to the map are persisted to disk + * (this is an operating system guarantee) independently from JVM process lifecycle. * - *

    Multiple containers could give access to the same data simultaneously, either inside a single JVM or - * across processes. Access is synchronized correctly across all instances, i. e. hash container mapping - * the data from the first JVM isn't able to modify the data, concurrently accessed from the second JVM by - * another hash container instance, mapping the same data. + *

    Multiple containers could give access to the same data simultaneously, either inside a + * single JVM or across processes. Access is synchronized correctly across all instances, i. e. + * hash container mapping the data from the first JVM isn't able to modify the data, + * concurrently accessed from the second JVM by another hash container instance, mapping the + * same data. * - *

    On container's {@link ChronicleHash#close() close()} the data isn't removed, it remains on disk and - * available to be opened again (given the same file name) or during different JVM run. + *

    On container's {@link ChronicleHash#close() close()} the data isn't removed, it remains on + * disk and available to be opened again (given the same file name) or during different JVM + * run. * *

    This method is shortcut for {@code instance().persistedTo(file).create()}. * - * @param file the file with existing hash container or a desired location of a new off-heap persisted - * hash container + * @param file the file with existing hash container or a desired location of a new off-heap + * persisted hash container * @return a hash container mapped to the given file - * @throws IOException if any IO error, related to off-heap memory allocation or file mapping, or - * establishing replication connections, occurs + * @throws IOException if any IO error, related to off-heap memory allocation or file mapping, + * or establishing replication connections, occurs * @see ChronicleHash#file() * @see ChronicleHash#close() * @see #create() diff --git a/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java b/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java index ef6781247..9f3fe647f 100755 --- a/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java +++ b/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java @@ -42,11 +42,11 @@ import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; /** - * {@code ChronicleSetBuilder} manages the whole set of {@link ChronicleSet} configurations, could be used as - * a classic builder and/or factory. + * {@code ChronicleSetBuilder} manages the whole set of {@link ChronicleSet} configurations, could + * be used as a classic builder and/or factory. * - *

    {@code ChronicleMapOnHeapUpdatableBuilder} is mutable, see a note in {@link ChronicleHashBuilder} - * interface documentation. + *

    {@code ChronicleMapOnHeapUpdatableBuilder} is mutable, see a note in {@link + * ChronicleHashBuilder} interface documentation. * * @param element type of the sets, created by this builder * @see ChronicleSet @@ -55,10 +55,10 @@ import java.util.concurrent.TimeUnit; public class ChronicleSetBuilder implements ChronicleHashBuilder, ChronicleSetBuilder> { - private ChronicleMapBuilder chronicleMapBuilderOnHeap; + private ChronicleMapBuilder chronicleMapBuilder; ChronicleSetBuilder(Class keyClass) { - chronicleMapBuilderOnHeap = ChronicleMapBuilder.of(keyClass, DummyValue.class) + chronicleMapBuilder = ChronicleMapBuilder.of(keyClass, DummyValue.class) .valueMarshallers(DummyValueMarshaller.INSTANCE, DummyValueMarshaller.INSTANCE) .valueSizeMarshaller(DummyValueMarshaller.INSTANCE); } @@ -72,7 +72,7 @@ public class ChronicleSetBuilder try { @SuppressWarnings("unchecked") final ChronicleSetBuilder result = (ChronicleSetBuilder) super.clone(); - result.chronicleMapBuilderOnHeap = chronicleMapBuilderOnHeap.clone(); + result.chronicleMapBuilder = chronicleMapBuilder.clone(); return result; } catch (CloneNotSupportedException e) { throw new AssertionError(e); @@ -81,19 +81,19 @@ public class ChronicleSetBuilder @Override public ChronicleSetBuilder actualSegments(int actualSegments) { - chronicleMapBuilderOnHeap.actualSegments(actualSegments); + chronicleMapBuilder.actualSegments(actualSegments); return this; } @Override public ChronicleSetBuilder minSegments(int minSegments) { - chronicleMapBuilderOnHeap.minSegments(minSegments); + chronicleMapBuilder.minSegments(minSegments); return this; } @Override public ChronicleSetBuilder actualEntriesPerSegment(long actualEntriesPerSegment) { - chronicleMapBuilderOnHeap.actualEntriesPerSegment(actualEntriesPerSegment); + chronicleMapBuilder.actualEntriesPerSegment(actualEntriesPerSegment); return this; } @@ -107,16 +107,16 @@ public class ChronicleSetBuilder * .keySize(10) * .create();} * - *

    (Note that 10 is chosen as key size in bytes despite strings in Java are UTF-16 encoded (and each - * character takes 2 bytes on-heap), because default off-heap {@link String} encoding is UTF-8 in {@code - * ChronicleSet}.) + *

    (Note that 10 is chosen as key size in bytes despite strings in Java are UTF-16 encoded + * (and each character takes 2 bytes on-heap), because default off-heap {@link String} encoding + * is UTF-8 in {@code ChronicleSet}.) * * @see #constantKeySizeBySample(Object) * @see #entrySize(int) */ @Override public ChronicleSetBuilder keySize(int keySize) { - chronicleMapBuilderOnHeap.keySize(keySize); + chronicleMapBuilder.keySize(keySize); return this; } @@ -132,55 +132,55 @@ public class ChronicleSetBuilder */ @Override public ChronicleSetBuilder constantKeySizeBySample(E sampleKey) { - chronicleMapBuilderOnHeap.constantKeySizeBySample(sampleKey); + chronicleMapBuilder.constantKeySizeBySample(sampleKey); return this; } /** * {@inheritDoc} * - *

    In fully default case you can expect entry size to be about 120-130 bytes. But it is strongly - * recommended always to configure {@linkplain #keySize(int) key size}, if they couldn't be derived - * statically. + *

    In fully default case you can expect entry size to be about 120-130 bytes. But it is + * strongly recommended always to configure {@linkplain #keySize(int) key size}, if they + * couldn't be derived statically. * *

    If entry size is not configured explicitly by calling this method, it is computed based on - * {@linkplain #metaDataBytes(int) meta data bytes}, plus {@linkplain #keySize(int) key size}, plus a few - * bytes required by implementations. + * {@linkplain #metaDataBytes(int) meta data bytes}, plus {@linkplain #keySize(int) key size}, + * plus a few bytes required by implementations. */ @Override public ChronicleSetBuilder entrySize(int entrySize) { - chronicleMapBuilderOnHeap.entrySize(entrySize); + chronicleMapBuilder.entrySize(entrySize); return this; } @Override public ChronicleSetBuilder entries(long entries) { - chronicleMapBuilderOnHeap.entries(entries); + chronicleMapBuilder.entries(entries); return this; } @Override public ChronicleSetBuilder lockTimeOut(long lockTimeOut, TimeUnit unit) { - chronicleMapBuilderOnHeap.lockTimeOut(lockTimeOut, unit); + chronicleMapBuilder.lockTimeOut(lockTimeOut, unit); return this; } @Override public ChronicleSetBuilder errorListener(ChronicleHashErrorListener errorListener) { - chronicleMapBuilderOnHeap.errorListener(errorListener); + chronicleMapBuilder.errorListener(errorListener); return this; } @Override public ChronicleSetBuilder metaDataBytes(int metaDataBytes) { - chronicleMapBuilderOnHeap.metaDataBytes(metaDataBytes); + chronicleMapBuilder.metaDataBytes(metaDataBytes); return this; } @Override public String toString() { return " ChronicleSetBuilder{" + - "chronicleMapBuilderOnHeap=" + chronicleMapBuilderOnHeap + + "chronicleMapBuilder=" + chronicleMapBuilder + '}'; } @@ -189,7 +189,7 @@ public class ChronicleSetBuilder public boolean equals(Object o) { if (!(o instanceof ChronicleSetBuilder)) return false; - return chronicleMapBuilderOnHeap.equals(((ChronicleSetBuilder) o).chronicleMapBuilderOnHeap); + return chronicleMapBuilder.equals(((ChronicleSetBuilder) o).chronicleMapBuilder); } @Override @@ -199,14 +199,14 @@ public class ChronicleSetBuilder @Override public ChronicleSetBuilder timeProvider(TimeProvider timeProvider) { - chronicleMapBuilderOnHeap.timeProvider(timeProvider); + chronicleMapBuilder.timeProvider(timeProvider); return this; } @Override public ChronicleSetBuilder bytesMarshallerFactory( BytesMarshallerFactory bytesMarshallerFactory) { - chronicleMapBuilderOnHeap.bytesMarshallerFactory(bytesMarshallerFactory); + chronicleMapBuilder.bytesMarshallerFactory(bytesMarshallerFactory); return this; } @@ -222,102 +222,103 @@ public class ChronicleSetBuilder */ @Override public ChronicleSetBuilder objectSerializer(ObjectSerializer objectSerializer) { - chronicleMapBuilderOnHeap.objectSerializer(objectSerializer); + chronicleMapBuilder.objectSerializer(objectSerializer); return this; } @Override public ChronicleSetBuilder keyMarshaller(@NotNull BytesMarshaller keyMarshaller) { - chronicleMapBuilderOnHeap.keyMarshaller(keyMarshaller); + chronicleMapBuilder.keyMarshaller(keyMarshaller); return this; } @Override public ChronicleSetBuilder keyMarshallers(@NotNull BytesWriter keyWriter, @NotNull BytesReader keyReader) { - chronicleMapBuilderOnHeap.keyMarshallers(keyWriter, keyReader); + chronicleMapBuilder.keyMarshallers(keyWriter, keyReader); return this; } @Override public ChronicleSetBuilder keySizeMarshaller(@NotNull SizeMarshaller keySizeMarshaller) { - chronicleMapBuilderOnHeap.keySizeMarshaller(keySizeMarshaller); + chronicleMapBuilder.keySizeMarshaller(keySizeMarshaller); return this; } /** * {@inheritDoc} * - *

    Actually this is just a convenience method supporting key marshaller configurations, made initially - * during {@link #of(Class)} call. Because if you {@linkplain #keyMarshaller(BytesMarshaller) configure} - * own custom key marshaller, this method doesn't take any effect on the maps constructed by this - * builder. + *

    Actually this is just a convenience method supporting key marshaller configurations, made + * initially during {@link #of(Class)} call. Because if you {@linkplain + * #keyMarshaller(BytesMarshaller) configure} own custom key marshaller, this method doesn't + * take any effect on the maps constructed by this builder. * * @see #of(Class) */ @Override public ChronicleSetBuilder keyDeserializationFactory( @NotNull ObjectFactory keyDeserializationFactory) { - chronicleMapBuilderOnHeap.keyDeserializationFactory(keyDeserializationFactory); + chronicleMapBuilder.keyDeserializationFactory(keyDeserializationFactory); return this; } @Override public ChronicleSetBuilder immutableKeys() { - chronicleMapBuilderOnHeap.immutableKeys(); + chronicleMapBuilder.immutableKeys(); return this; } @Override public ChronicleSetBuilder replication(SingleChronicleHashReplication replication) { - chronicleMapBuilderOnHeap.replication(replication); + chronicleMapBuilder.replication(replication); return this; } @Override public ChronicleSetBuilder replication(byte identifier, TcpTransportAndNetworkConfig tcpTransportAndNetwork) { - chronicleMapBuilderOnHeap.replication(identifier, tcpTransportAndNetwork); + chronicleMapBuilder.replication(identifier, tcpTransportAndNetwork); return this; } @Override public ChronicleSetBuilder replication(byte identifier) { - chronicleMapBuilderOnHeap.replication(identifier); + chronicleMapBuilder.replication(identifier); return this; } @Override public StatelessClientConfig> statelessClient( InetSocketAddress remoteAddress) { - return new StatelessSetConfig<>(chronicleMapBuilderOnHeap.statelessClient(remoteAddress)); + return new StatelessSetConfig<>(chronicleMapBuilder.statelessClient(remoteAddress)); } @Override public ChronicleHashInstanceConfig> instance() { - return new InstanceConfig<>(chronicleMapBuilderOnHeap.instance()); + return new InstanceConfig<>(chronicleMapBuilder.instance()); } @Override public ChronicleSet create() throws IOException { - final ChronicleMap map = chronicleMapBuilderOnHeap.create(); + final ChronicleMap map = chronicleMapBuilder.create(); return new SetFromMap(map); } @Override public ChronicleSet createPersistedTo(File file) throws IOException { - ChronicleMap map = chronicleMapBuilderOnHeap.createPersistedTo(file); + ChronicleMap map = chronicleMapBuilder.createPersistedTo(file); return new SetFromMap(map); } @Override public String name() { - return chronicleMapBuilderOnHeap.name(); + return chronicleMapBuilder.name(); } public ChronicleSetBuilder name(String name) { - chronicleMapBuilderOnHeap.name(name); + chronicleMapBuilder.name(name); return this; } + } diff --git a/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java b/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java index e4b9c1e56..6a815f783 100644 --- a/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java +++ b/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java @@ -31,31 +31,32 @@ public class CHMTestIterator1 { AtomicLong alKey = new AtomicLong(); int runs = 3000000; ChronicleMapBuilder builder = ChronicleMapBuilder.of(String.class, Long.class) + .entries(runs); - ChronicleMap chm = builder.create(); + try (ChronicleMap chm = builder.create()) { /*chm.put("k1", alValue.incrementAndGet()); chm.put("k2", alValue.incrementAndGet()); chm.put("k3", alValue.incrementAndGet()); chm.put("k4", alValue.incrementAndGet()); chm.put("k5", alValue.incrementAndGet());*/ - //chm.keySet(); + //chm.keySet(); - for (int i = 0; i < runs; i++) { - chm.put("k" + alKey.incrementAndGet(), alValue.incrementAndGet()); - } + for (int i = 0; i < runs; i++) { + chm.put("k" + alKey.incrementAndGet(), alValue.incrementAndGet()); + } - long start = System.nanoTime(); - for (Map.Entry entry : chm.entrySet()) { - entry.getKey(); - entry.getValue(); + long start = System.nanoTime(); + for (Map.Entry entry : chm.entrySet()) { + entry.getKey(); + entry.getValue(); + + } + long time = System.nanoTime() - start; + System.out.println("Average iteration time was " + time / runs / 1e3 + "us, for " + runs / 1e6 + "m entries"); } - long time = System.nanoTime() - start; - System.out.println("Average iteration time was " + time / runs / 1e3 + "us, for " + runs / 1e6 + "m entries"); - - } diff --git a/src/test/java/net/openhft/chronicle/map/ChannelReplicationTest.java b/src/test/java/net/openhft/chronicle/map/ChannelReplicationTest.java index dff303bf2..efc57b810 100644 --- a/src/test/java/net/openhft/chronicle/map/ChannelReplicationTest.java +++ b/src/test/java/net/openhft/chronicle/map/ChannelReplicationTest.java @@ -88,6 +88,7 @@ public class ChannelReplicationTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java b/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java index 78ab35c73..7605dbc3a 100644 --- a/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java +++ b/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java @@ -52,17 +52,18 @@ public class ConstantSizeBySampleTest { @Test public void testUnexpectedlyLongConstantByteArrayValues() throws IOException { - ChronicleMap map = ChronicleMapBuilder.of(Long.class, byte[].class) + try (ChronicleMap map = ChronicleMapBuilder.of(Long.class, byte[].class) .constantValueSizeBySample(new byte[512 * 1024]) .entries(100) .actualSegments(1) - .create(); + .create()) { - byte[] value = new byte[512 * 1024]; + byte[] value = new byte[512 * 1024]; - value[42] = 1; - map.put(1L, value); - Assert.assertTrue(Arrays.equals(map.get(1L), value)); + value[42] = 1; + map.put(1L, value); + Assert.assertTrue(Arrays.equals(map.get(1L), value)); + } } static class ExternalizableData implements Externalizable { @@ -88,17 +89,18 @@ public class ConstantSizeBySampleTest { @Test public void testUnexpectedlyLongConstantExternalizableValues() throws IOException { - ChronicleMap map = + try ( ChronicleMap map = ChronicleMapBuilder.of(Long.class, ExternalizableData.class) .constantValueSizeBySample(new ExternalizableData()) .entries(100) .actualSegments(1) - .create(); + .create()) { - ExternalizableData value = new ExternalizableData(); - value.data[42] = 1; - map.put(1L, value); - Assert.assertEquals(map.get(1L), value); + ExternalizableData value = new ExternalizableData(); + value.data[42] = 1; + map.put(1L, value); + Assert.assertEquals(map.get(1L), value); + } } static class SerializableData implements Serializable { @@ -115,16 +117,17 @@ public class ConstantSizeBySampleTest { @Test @Ignore public void testUnexpectedlyLongConstantSerializableValues() throws IOException { - ChronicleMap map = + try ( ChronicleMap map = ChronicleMapBuilder.of(Long.class, SerializableData.class) .constantValueSizeBySample(new SerializableData()) .entries(100) .actualSegments(1) - .create(); + .create()) { - SerializableData value = new SerializableData(); - value.data[42] = 1; - map.put(1L, value); - Assert.assertEquals(map.get(1L), value); + SerializableData value = new SerializableData(); + value.data[42] = 1; + map.put(1L, value); + Assert.assertEquals(map.get(1L), value); + } } } diff --git a/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java b/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java index c970ab11c..ed5f40bbc 100755 --- a/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java @@ -17,85 +17,88 @@ public class DemoChronicleMapTest { File file = File.createTempFile("DummyOrders", ".test"); file.deleteOnExit(); int maxEntries = 1000; - ChronicleMap map = ChronicleMapBuilder + try (ChronicleMap map = ChronicleMapBuilder .of(IntValue.class, DemoOrderVOInterface.class) .putReturnsNull(true) .removeReturnsNull(true) .entries(maxEntries) - .createPersistedTo(file); + .createPersistedTo(file)) { - IntValue key = DataValueClasses.newDirectInstance(IntValue.class); + IntValue key = DataValueClasses.newDirectInstance(IntValue.class); - DemoOrderVOInterface value = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); - DemoOrderVOInterface value2 = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); + DemoOrderVOInterface value = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); + DemoOrderVOInterface value2 = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); - // Initially populate the map - for (int i = 0; i < maxEntries; i++) { - key.setValue(i); + // Initially populate the map + for (int i = 0; i < maxEntries; i++) { + key.setValue(i); - map.acquireUsing(key, value); + map.acquireUsing(key, value); - value.setSymbol("IBM-" + i); - value.addAtomicOrderQty(1000); + value.setSymbol("IBM-" + i); + value.addAtomicOrderQty(1000); - map.getUsing(key, value2); - assertEquals("IBM-" + i, value.getSymbol()); - assertEquals(1000, value.getOrderQty(), 0.0); - } + map.getUsing(key, value2); + assertEquals("IBM-" + i, value.getSymbol()); + assertEquals(1000, value.getOrderQty(), 0.0); + } - for (Map.Entry entry : map.entrySet()) { + for (Map.Entry entry : map.entrySet()) { - IntValue k = entry.getKey(); - DemoOrderVOInterface v = entry.getValue(); + IntValue k = entry.getKey(); + DemoOrderVOInterface v = entry.getValue(); - System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); - assertNotNull(v); + System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); + assertNotNull(v); + } } } + @Test public void testMapLocked() throws Exception { File file = File.createTempFile("DummyOrders", ".test"); file.deleteOnExit(); int maxEntries = 1000; - ChronicleMap map = ChronicleMapBuilder + try (ChronicleMap map = ChronicleMapBuilder .of(IntValue.class, DemoOrderVOInterface.class) .putReturnsNull(true) .removeReturnsNull(true) .entries(maxEntries) - .createPersistedTo(file); + .createPersistedTo(file)) { - IntValue key = DataValueClasses.newDirectInstance(IntValue.class); + IntValue key = DataValueClasses.newDirectInstance(IntValue.class); - DemoOrderVOInterface value = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); - DemoOrderVOInterface value2 = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); + DemoOrderVOInterface value = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); + DemoOrderVOInterface value2 = DataValueClasses.newDirectReference(DemoOrderVOInterface.class); - // Initially populate the map - for (int i = 0; i < maxEntries; i++) { - key.setValue(i); + // Initially populate the map + for (int i = 0; i < maxEntries; i++) { + key.setValue(i); - try (WriteContext wc = map.acquireUsingLocked(key, value)) { - value.setSymbol("IBM-" + i); - value.addAtomicOrderQty(1000); + try (WriteContext wc = map.acquireUsingLocked(key, value)) { + value.setSymbol("IBM-" + i); + value.addAtomicOrderQty(1000); + } + + try (ReadContext rc = map.getUsingLocked(key, value2)) { + assertTrue(rc.present()); + assertEquals("IBM-" + i, value.getSymbol()); + assertEquals(1000, value.getOrderQty(), 0.0); + } } - try (ReadContext rc = map.getUsingLocked(key, value2)) { - assertTrue(rc.present()); - assertEquals("IBM-" + i, value.getSymbol()); - assertEquals(1000, value.getOrderQty(), 0.0); + for (Map.Entry entry : map.entrySet()) { + + IntValue k = entry.getKey(); + DemoOrderVOInterface v = entry.getValue(); + + System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); + assertNotNull(v); } } - - for (Map.Entry entry : map.entrySet()) { - - IntValue k = entry.getKey(); - DemoOrderVOInterface v = entry.getValue(); - - System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); - assertNotNull(v); - } } } diff --git a/src/test/java/net/openhft/chronicle/map/EventListenerTestWithTCPSocketReplication.java b/src/test/java/net/openhft/chronicle/map/EventListenerTestWithTCPSocketReplication.java index af9848ef4..1959daa06 100644 --- a/src/test/java/net/openhft/chronicle/map/EventListenerTestWithTCPSocketReplication.java +++ b/src/test/java/net/openhft/chronicle/map/EventListenerTestWithTCPSocketReplication.java @@ -87,6 +87,7 @@ public class EventListenerTestWithTCPSocketReplication { valueRef.set(null); replacedValueRef.set(null); keyRef.set(null); + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java b/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java index 597bb622e..7cba0cd86 100644 --- a/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java @@ -37,22 +37,24 @@ public class IntValueMapTest { @Test public void test() throws IOException { - final ChronicleMap map = OnHeapUpdatableChronicleMapBuilder + try (final ChronicleMap map = OnHeapUpdatableChronicleMapBuilder .of(IntValue.class, CharSequence.class) .entries(20000) - .keyMarshaller(ByteableIntValueMarshaller.INSTANCE).create(); + .keyMarshaller(ByteableIntValueMarshaller.INSTANCE).create()) { - IntValue$$Native value = new IntValue$$Native(); - value.bytes(new ByteBufferBytes(ByteBuffer.allocateDirect(4)), 0); + IntValue$$Native value = new IntValue$$Native(); + value.bytes(new ByteBufferBytes(ByteBuffer.allocateDirect(4)), 0); - value.setValue(1); - final String expected = "test"; - map.put(value, expected); + value.setValue(1); + final String expected = "test"; + map.put(value, expected); - final CharSequence actual = map.get(value); - assertEquals(expected, actual); + final CharSequence actual = map.get(value); + assertEquals(expected, actual); - // this will fail - map.toString(); + // this will fail + + map.toString(); + } } } diff --git a/src/test/java/net/openhft/chronicle/map/Issue42Test.java b/src/test/java/net/openhft/chronicle/map/Issue42Test.java index 4b1681623..c9d0800ef 100755 --- a/src/test/java/net/openhft/chronicle/map/Issue42Test.java +++ b/src/test/java/net/openhft/chronicle/map/Issue42Test.java @@ -32,22 +32,22 @@ public class Issue42Test { if (!Jvm.isWindows()) return; - final ChronicleMap map = OnHeapUpdatableChronicleMapBuilder + try (final ChronicleMap map = OnHeapUpdatableChronicleMapBuilder .of(CharSequence.class, CharSequence.class) .entrySize(18) .entries(1500000) - .minSegments(128).create(); + .minSegments(128).create()) { - for (int i = 0; i < 1000000; ++i) { - String s = String.valueOf(i); - map.put(s, s); + for (int i = 0; i < 1000000; ++i) { + String s = String.valueOf(i); + map.put(s, s); + } + + for (int i = 0; i < 1000000; ++i) { + String s = String.valueOf(i); + Assert.assertEquals(s, map.get(s)); + } } - for (int i = 0; i < 1000000; ++i) { - String s = String.valueOf(i); - Assert.assertEquals(s, map.get(s)); - } - - map.close(); } } diff --git a/src/test/java/net/openhft/chronicle/map/PostChannelCreationTest.java b/src/test/java/net/openhft/chronicle/map/PostChannelCreationTest.java index a7db4b5fc..d7d95e72f 100644 --- a/src/test/java/net/openhft/chronicle/map/PostChannelCreationTest.java +++ b/src/test/java/net/openhft/chronicle/map/PostChannelCreationTest.java @@ -111,6 +111,7 @@ public class PostChannelCreationTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/SingleMapChannelTest.java b/src/test/java/net/openhft/chronicle/map/SingleMapChannelTest.java index ac5062742..4a16a5ceb 100644 --- a/src/test/java/net/openhft/chronicle/map/SingleMapChannelTest.java +++ b/src/test/java/net/openhft/chronicle/map/SingleMapChannelTest.java @@ -104,6 +104,7 @@ public class SingleMapChannelTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/StatelessClientTest.java b/src/test/java/net/openhft/chronicle/map/StatelessClientTest.java index 08928a07d..78a3707f8 100644 --- a/src/test/java/net/openhft/chronicle/map/StatelessClientTest.java +++ b/src/test/java/net/openhft/chronicle/map/StatelessClientTest.java @@ -52,6 +52,7 @@ public class StatelessClientTest { try (ChronicleMap serverMap = ChronicleMapBuilder.of(Integer.class, StringBuilder.class) + .putReturnsNull(true) .defaultValue(new StringBuilder()) .replication((byte) 2, TcpTransportAndNetworkConfig.of(8056)).create()) { @@ -59,6 +60,7 @@ public class StatelessClientTest { try (ChronicleMap statelessMap = ChronicleMapBuilder.of(Integer .class, StringBuilder.class) + .putReturnsNull(true) .statelessClient(new InetSocketAddress("localhost", 8056)).create()) { String actual = statelessMap.mapForKey(10, ToString.INSTANCE); diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3VoidValueTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3VoidValueTest.java index 960f47deb..722b48b03 100755 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3VoidValueTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3VoidValueTest.java @@ -60,6 +60,7 @@ public class TCPSocketReplication3VoidValueTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3wayPutReturnsNullTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3wayPutReturnsNullTest.java index 932f1fc55..4049a71b2 100755 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3wayPutReturnsNullTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplication3wayPutReturnsNullTest.java @@ -75,6 +75,7 @@ public class TCPSocketReplication3wayPutReturnsNullTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplication4WayMapTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplication4WayMapTest.java index 38ce5cde0..b84511c7e 100644 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplication4WayMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplication4WayMapTest.java @@ -73,6 +73,7 @@ public class TCPSocketReplication4WayMapTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationBootStrapTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationBootStrapTest.java index 69f4937fe..5945f2263 100644 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationBootStrapTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationBootStrapTest.java @@ -152,6 +152,7 @@ public class TCPSocketReplicationBootStrapTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationIntValueTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationIntValueTest.java index 93429dd23..986df23f3 100644 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationIntValueTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationIntValueTest.java @@ -77,6 +77,8 @@ public class TCPSocketReplicationIntValueTest { e.printStackTrace(); } } + + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationNativeTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationNativeTest.java index a2679b4fe..9d7f7fa33 100644 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationNativeTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationNativeTest.java @@ -74,6 +74,7 @@ public class TCPSocketReplicationNativeTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationPostConnectionTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationPostConnectionTest.java index 2a931292b..b6d5c4093 100644 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationPostConnectionTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationPostConnectionTest.java @@ -117,6 +117,7 @@ public class TCPSocketReplicationPostConnectionTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationTest.java b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationTest.java index f8e8f7a52..5da3abbf5 100644 --- a/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationTest.java +++ b/src/test/java/net/openhft/chronicle/map/TCPSocketReplicationTest.java @@ -64,6 +64,7 @@ public class TCPSocketReplicationTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/TestBooleanValues.java b/src/test/java/net/openhft/chronicle/map/TestBooleanValues.java index eff5fa333..4eba46b99 100644 --- a/src/test/java/net/openhft/chronicle/map/TestBooleanValues.java +++ b/src/test/java/net/openhft/chronicle/map/TestBooleanValues.java @@ -34,10 +34,11 @@ public class TestBooleanValues { */ @Test public void testTestBooleanValues() throws IOException, InterruptedException { - ChronicleMap map = - ChronicleMapBuilder.of(Integer.class, Boolean.class).create(); - map.put(7, true); - Assert.assertEquals(true, map.get(7)); + try (ChronicleMap map = + ChronicleMapBuilder.of(Integer.class, Boolean.class).create()) { + map.put(7, true); + Assert.assertEquals(true, map.get(7)); + } } } diff --git a/src/test/java/net/openhft/chronicle/map/TimeBasedReplicationTest.java b/src/test/java/net/openhft/chronicle/map/TimeBasedReplicationTest.java index b954de03d..bae6ed43f 100644 --- a/src/test/java/net/openhft/chronicle/map/TimeBasedReplicationTest.java +++ b/src/test/java/net/openhft/chronicle/map/TimeBasedReplicationTest.java @@ -49,154 +49,156 @@ public class TimeBasedReplicationTest extends JSR166TestCase { public void testIgnoreALatePut() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) - .replication((byte)1) - .create(); + .replication((byte) 1) + .create()) { - current(timeProvider); + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - assertEquals(map.size(), 1); - assertEquals(map.get("key-1"), "value-1"); + // we do a put at the current time + map.put("key-1", "value-1"); + assertEquals(map.size(), 1); + assertEquals(map.get("key-1"), "value-1"); - // now test assume that we receive a late update to the map, the following update should be ignored - late(timeProvider); + // now test assume that we receive a late update to the map, the following update should be ignored + late(timeProvider); - map.put("key-1", "value-2"); - - // we'll now flip the time back to the current in order to do the read the result - current(timeProvider); - assertEquals(map.size(), 1); - assertEquals(map.get("key-1"), "value-1"); + map.put("key-1", "value-2"); + // we'll now flip the time back to the current in order to do the read the result + current(timeProvider); + assertEquals(map.size(), 1); + assertEquals(map.get("key-1"), "value-1"); + } } @Test public void testIgnoreALatePutIfAbsent() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) - .replication((byte)1) - .create(); - current(timeProvider); + .replication((byte) 1) + .create()) { + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - assertEquals(map.size(), 1); - assertEquals(map.get("key-1"), "value-1"); + // we do a put at the current time + map.put("key-1", "value-1"); + assertEquals(map.size(), 1); + assertEquals(map.get("key-1"), "value-1"); - // now test assume that we receive a late update to the map, the following update should be ignored - late(timeProvider); + // now test assume that we receive a late update to the map, the following update should be ignored + late(timeProvider); - final Object o = map.putIfAbsent("key-1", "value-2"); - assertEquals(o, null); - - // we'll now flip the time back to the current in order to do the read the result - current(timeProvider); - assertEquals(1, map.size()); - assertEquals(map.get("key-1"), "value-1"); + final Object o = map.putIfAbsent("key-1", "value-2"); + assertEquals(o, null); + // we'll now flip the time back to the current in order to do the read the result + current(timeProvider); + assertEquals(1, map.size()); + assertEquals(map.get("key-1"), "value-1"); + } } @Test public void testIgnoreALateReplace() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) - .replication((byte)1) - .create(); + .replication((byte) 1) + .create()) { - current(timeProvider); + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); + // we do a put at the current time + map.put("key-1", "value-1"); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); - // now test assume that we receive a late update to the map, - // the following update should be ignored - late(timeProvider); + // now test assume that we receive a late update to the map, + // the following update should be ignored + late(timeProvider); - final Object o = map.replace("key-1", "value-2"); - assertEquals(o, null); + final Object o = map.replace("key-1", "value-2"); + assertEquals(o, null); - // we'll now flip the time back to the current in order to do the read the result - current(timeProvider); - assertEquals(map.size(), 1); - assertEquals("value-1", map.get("key-1")); + // we'll now flip the time back to the current in order to do the read the result + current(timeProvider); + assertEquals(map.size(), 1); + assertEquals("value-1", map.get("key-1")); + } } @Test public void testIgnoreALateReplaceWithValue() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) .replication((byte) 1) - .create(); + .create()) { - current(timeProvider); + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); + // we do a put at the current time + map.put("key-1", "value-1"); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); - // now test assume that we receive a late update to the map, the following update should be ignored - late(timeProvider); + // now test assume that we receive a late update to the map, the following update should be ignored + late(timeProvider); - assertEquals(null, map.replace("key-1", "value-2")); + assertEquals(null, map.replace("key-1", "value-2")); - // we'll now flip the time back to the current in order to do the read the result - current(timeProvider); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); - + // we'll now flip the time back to the current in order to do the read the result + current(timeProvider); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); + } } @Test public void testIgnoreALateRemoveWithValue() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) .replication((byte) 1) - .create(); + .create()) { - current(timeProvider); + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); + // we do a put at the current time + map.put("key-1", "value-1"); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); - // now test assume that we receive a late update to the map, the following update should be ignored - late(timeProvider); + // now test assume that we receive a late update to the map, the following update should be ignored + late(timeProvider); - assertEquals(false, map.remove("key-1", "value-1")); + assertEquals(false, map.remove("key-1", "value-1")); - // we'll now flip the time back to the current in order to do the read the result - current(timeProvider); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); + // we'll now flip the time back to the current in order to do the read the result + current(timeProvider); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); + } } @@ -204,11 +206,11 @@ public class TimeBasedReplicationTest extends JSR166TestCase { public void testIgnoreALateRemove() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) .replication((byte) 1) - .create(); + .create()) { current(timeProvider); @@ -226,37 +228,40 @@ public class TimeBasedReplicationTest extends JSR166TestCase { current(timeProvider); assertEquals(1, map.size()); assertEquals("value-1", map.get("key-1")); - } +} + @Test public void testIgnoreWithRemoteRemove() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ReplicatedChronicleMap map = (ReplicatedChronicleMap) ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ReplicatedChronicleMap map = (ReplicatedChronicleMap) ChronicleMapBuilder.of + (CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) .replication((byte) 1) - .create(); + .create()) { - current(timeProvider); + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); + // we do a put at the current time + map.put("key-1", "value-1"); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); - // now test assume that we receive a late update to the map, the following update should be ignored - final long late = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(5); - assertEquals(null, map.remove("key-1", "value-2", IDENTIFIER, late)); + // now test assume that we receive a late update to the map, the following update should be ignored + final long late = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(5); + assertEquals(null, map.remove("key-1", "value-2", IDENTIFIER, late)); - // we'll now flip the time back to the current in order to do the read the result - current(timeProvider); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); - assertTrue(map.containsValue("value-1")); - assertFalse(map.containsValue("value-2")); + // we'll now flip the time back to the current in order to do the read the result + current(timeProvider); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); + assertTrue(map.containsValue("value-1")); + assertFalse(map.containsValue("value-2")); + } } @@ -265,30 +270,33 @@ public class TimeBasedReplicationTest extends JSR166TestCase { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ReplicatedChronicleMap map = (ReplicatedChronicleMap) ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ReplicatedChronicleMap map = (ReplicatedChronicleMap) ChronicleMapBuilder.of + (CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) .replication((byte) 1) - .create(); + .create()) { - current(timeProvider); + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - assertEquals(1, map.size()); - assertEquals("value-1", map.get("key-1")); + // we do a put at the current time + map.put("key-1", "value-1"); + assertEquals(1, map.size()); + assertEquals("value-1", map.get("key-1")); - // now test assume that we receive a late update to the map, the following update should be ignored - // now test assume that we receive a late update to the map, the following update should be ignored - final long late = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(5); - assertEquals(null, map.put("key-1", "value-2", IDENTIFIER, late)); + // now test assume that we receive a late update to the map, the following update should be ignored + // now test assume that we receive a late update to the map, the following update should be ignored + final long late = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(5); + assertEquals(null, map.put("key-1", "value-2", IDENTIFIER, late)); - // we'll now flip the time back to the current in order to do the read the result - current(timeProvider); + // we'll now flip the time back to the current in order to do the read the result + current(timeProvider); - assertEquals("value-1", map.get("key-1")); - assertEquals(1, map.size(), 0); + assertEquals("value-1", map.get("key-1")); + assertEquals(1, map.size(), 0); + + } } @@ -296,28 +304,30 @@ public class TimeBasedReplicationTest extends JSR166TestCase { public void testRemoveFollowedByLatePut() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ReplicatedChronicleMap map = (ReplicatedChronicleMap) ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ReplicatedChronicleMap map = (ReplicatedChronicleMap) ChronicleMapBuilder.of + (CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) - .replication((byte)1) - .create(); + .replication((byte) 1) + .create()) { - current(timeProvider); + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - map.remove("key-1", "value-1"); - assertEquals(0, map.size()); - assertEquals(null, map.get("key-1")); - assertEquals(false, map.containsKey("key-1")); + // we do a put at the current time + map.put("key-1", "value-1"); + map.remove("key-1", "value-1"); + assertEquals(0, map.size()); + assertEquals(null, map.get("key-1")); + assertEquals(false, map.containsKey("key-1")); - // test assume that we receive a late update to the map, the following update should be ignored - final long late = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(50); - assertEquals(null, map.put("key-1", "value-2", IDENTIFIER, late)); + // test assume that we receive a late update to the map, the following update should be ignored + final long late = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(50); + assertEquals(null, map.put("key-1", "value-2", IDENTIFIER, late)); - assertEquals(null, map.get("key-1")); - assertEquals(false, map.containsKey("key-1")); - assertEquals(0, map.size(), 0); + assertEquals(null, map.get("key-1")); + assertEquals(false, map.containsKey("key-1")); + assertEquals(0, map.size(), 0); + } } @@ -325,21 +335,22 @@ public class TimeBasedReplicationTest extends JSR166TestCase { public void testPutRemovePut() throws IOException { final TimeProvider timeProvider = Mockito.mock(TimeProvider.class); - ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) + try (ChronicleMap map = ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(10) .timeProvider(timeProvider) - .replication((byte)1) - .create(); - current(timeProvider); + .replication((byte) 1) + .create()) { + current(timeProvider); - // we do a put at the current time - map.put("key-1", "value-1"); - map.remove("key-1"); - assertEquals(0, map.size()); - assertEquals(null, map.put("key-1", "new-value-2")); - assertEquals(true, map.containsKey("key-1")); - assertEquals("new-value-2", map.get("key-1")); - assertEquals(1, map.size(), 0); + // we do a put at the current time + map.put("key-1", "value-1"); + map.remove("key-1"); + assertEquals(0, map.size()); + assertEquals(null, map.put("key-1", "new-value-2")); + assertEquals(true, map.containsKey("key-1")); + assertEquals("new-value-2", map.get("key-1")); + assertEquals(1, map.size(), 0); + } } private void current(TimeProvider timeProvider) { diff --git a/src/test/java/net/openhft/chronicle/map/TwoMapOnDifferentServersTest.java b/src/test/java/net/openhft/chronicle/map/TwoMapOnDifferentServersTest.java index b3059df03..d06cd56b5 100644 --- a/src/test/java/net/openhft/chronicle/map/TwoMapOnDifferentServersTest.java +++ b/src/test/java/net/openhft/chronicle/map/TwoMapOnDifferentServersTest.java @@ -70,6 +70,7 @@ public class TwoMapOnDifferentServersTest { e.printStackTrace(); } } + System.gc(); } diff --git a/src/test/java/net/openhft/chronicle/map/UDPSocketReplicationTest.java b/src/test/java/net/openhft/chronicle/map/UDPSocketReplicationTest.java index 4f44e0b29..b1dac4869 100644 --- a/src/test/java/net/openhft/chronicle/map/UDPSocketReplicationTest.java +++ b/src/test/java/net/openhft/chronicle/map/UDPSocketReplicationTest.java @@ -72,11 +72,12 @@ public class UDPSocketReplicationTest { e.printStackTrace(); } } + System.gc(); } /* @Test - // @Ignore + @Ignore public void testBufferOverflow() throws IOException, InterruptedException { for (int i = 0; i < 1024; i++) { @@ -85,8 +86,7 @@ public class UDPSocketReplicationTest { System.out.println("" + map2); } - } -*/ + }*/ } diff --git a/src/test/java/net/openhft/chronicle/map/example/DistributedSequenceMain.java b/src/test/java/net/openhft/chronicle/map/example/DistributedSequenceMain.java index 13f03e882..d7bd7355d 100644 --- a/src/test/java/net/openhft/chronicle/map/example/DistributedSequenceMain.java +++ b/src/test/java/net/openhft/chronicle/map/example/DistributedSequenceMain.java @@ -29,17 +29,16 @@ public class DistributedSequenceMain { public static void main(String... ignored) throws IOException { Class longValueClass = DataValueClasses.directClassFor(LongValue.class); - ChronicleMap map = - ChronicleMapBuilder.of(String.class, longValueClass) - .entries(128) - .actualSegments(1).create(); - LongValue value = DataValueClasses.newDirectReference(longValueClass); - map.acquireUsing("sequence", value); + try (ChronicleMap map = + ChronicleMapBuilder.of(String.class, longValueClass) + .entries(128) + .actualSegments(1).create()) { + LongValue value = DataValueClasses.newDirectReference(longValueClass); + map.acquireUsing("sequence", value); - for (int i = 0; i < 1000000; i++) { - long nextId = value.addAtomicValue(1); + for (int i = 0; i < 1000000; i++) { + long nextId = value.addAtomicValue(1); + } } - - map.close(); } } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/StringEncodingExamplesTest.java b/src/test/java/net/openhft/chronicle/map/fromdocs/StringEncodingExamplesTest.java index e797d5e35..86376bd1f 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/StringEncodingExamplesTest.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/StringEncodingExamplesTest.java @@ -18,7 +18,6 @@ package net.openhft.chronicle.map.fromdocs; -import net.openhft.lang.threadlocal.StatefulCopyable; import net.openhft.chronicle.set.ChronicleSet; import net.openhft.chronicle.set.ChronicleSetBuilder; import net.openhft.lang.io.Bytes; @@ -26,12 +25,16 @@ import net.openhft.lang.io.CharBuffers; import net.openhft.lang.io.serialization.BytesMarshaller; import net.openhft.lang.model.constraints.NotNull; import net.openhft.lang.pool.CharSequenceInterner; +import net.openhft.lang.threadlocal.StatefulCopyable; import org.jetbrains.annotations.Nullable; import org.junit.Assert; import org.junit.Test; -import java.io.*; -import java.nio.*; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; @@ -186,18 +189,19 @@ public class StringEncodingExamplesTest { private void testCustomKeyMarshaller(BytesMarshaller marshaller) throws IOException { - ChronicleSet chineseWordSet = ChronicleSetBuilder.of(CharSequence.class) + try (ChronicleSet chineseWordSet = ChronicleSetBuilder.of(CharSequence.class) .keyMarshaller(marshaller) .actualSegments(1) .actualEntriesPerSegment(1000) - .create(); + .create()) { - chineseWordSet.add("新闻"); - chineseWordSet.add("地图"); - chineseWordSet.add("贴吧"); - chineseWordSet.add("登录"); - chineseWordSet.add("设置"); - Assert.assertEquals(5, chineseWordSet.size()); - System.out.println(chineseWordSet); + chineseWordSet.add("新闻"); + chineseWordSet.add("地图"); + chineseWordSet.add("贴吧"); + chineseWordSet.add("登录"); + chineseWordSet.add("设置"); + Assert.assertEquals(5, chineseWordSet.size()); + System.out.println(chineseWordSet); + } } } diff --git a/src/test/java/net/openhft/chronicle/map/jrs166/JSR166TestCase.java b/src/test/java/net/openhft/chronicle/map/jrs166/JSR166TestCase.java index 0f0f9445e..4471e2ab5 100644 --- a/src/test/java/net/openhft/chronicle/map/jrs166/JSR166TestCase.java +++ b/src/test/java/net/openhft/chronicle/map/jrs166/JSR166TestCase.java @@ -284,6 +284,7 @@ public class JSR166TestCase { throw new AssertionFailedError("interrupt status set in main thread"); checkForkJoinPoolThreadLeaks(); + System.gc(); } /** diff --git a/src/test/java/net/openhft/chronicle/map/jrs166/map/ChronicleMapTest.java b/src/test/java/net/openhft/chronicle/map/jrs166/map/ChronicleMapTest.java index c3665fa8c..13a9a6f01 100644 --- a/src/test/java/net/openhft/chronicle/map/jrs166/map/ChronicleMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/jrs166/map/ChronicleMapTest.java @@ -54,6 +54,9 @@ public class ChronicleMapTest extends JSR166TestCase { } + + + static ChronicleMap newShmListBoolean(int size) throws IOException { return ChronicleMapBuilder.of(ArrayList.class, CharSequence.class) .entries(size).create(); @@ -64,7 +67,7 @@ public class ChronicleMapTest extends JSR166TestCase { return ChronicleMapBuilder.of(ArrayList.class, CharSequence.class).create(); } - static ChronicleMap newShmStringString(int size) throws IOException { + static ChronicleMap newStrStrMap(int size) throws IOException { return ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .entries(size).create(); } @@ -94,415 +97,394 @@ public class ChronicleMapTest extends JSR166TestCase { return map; } + + /** * clear removes all pairs */ - @Test + @Test(timeout = 5000) public void testClear() throws IOException { - ChronicleMap map = map5(); - map.clear(); - assertEquals(0, map.size()); - } + try (ChronicleMap map = map5()) { - /** - * Maps with same contents are equal - */ - @Test - public void testEquals() throws IOException { - ChronicleMap map1 = map5(); - ChronicleMap map2 = map5(); - assertEquals(map1, map2); - assertEquals(map2, map1); - map1.clear(); - assertFalse(map1.equals(map2)); - assertFalse(map2.equals(map1)); + map.clear(); + assertEquals(0, map.size()); + + } } /** * contains returns true for contained value */ - @Test + @Test(timeout = 5000) public void testContains() throws IOException { - ChronicleMap map = map5(); - assertTrue(map.containsValue("A")); - assertFalse(map.containsValue("Z")); + try (ChronicleMap map = map5()) { + assertTrue(map.containsValue("A")); + assertFalse(map.containsValue("Z")); + } + } /** * containsKey returns true for contained key */ - @Test + @Test(timeout = 5000) public void testContainsKey() throws IOException { - ChronicleMap map = map5(); - assertTrue(map.containsKey(one)); - assertFalse(map.containsKey(zero)); + try (ChronicleMap map = map5()) { + assertTrue(map.containsKey(one)); + assertFalse(map.containsKey(zero)); + } } /** * containsValue returns true for held values */ - @Test + @Test(timeout = 5000) public void testContainsValue() throws IOException { - ChronicleMap map = map5(); - assertTrue(map.containsValue("A")); - assertFalse(map.containsValue("Z")); - } - - - /** - * Inserted elements that are subclasses of the same Comparable - * class are found. - */ - /* @Test public void testComparableFamily() throws IOException { - ChronicleMap m = - newShmBiBoolean(); - for (int i = 0; i < 1000; i++) { - assertTrue(m.put(new CI(i), true) == null); - } - for (int i = 0; i < 1000; i++) { - assertTrue(m.containsKey(new CI(i))); - assertTrue(m.containsKey(new DI(i))); - } - }*/ - - /** - * TODO : fix test - * Elements of classes with erased generic type parameters based - * on Comparable can be inserted and found. - */ - /* @Test public void testGenericComparable() throws IOException { - ChronicleMap m = - newShmBiBoolean(); - for (int i = 0; i < 1000; i++) { - BI bi = new BI(i); - BS bs = new BS(String.valueOf(i)); - LexicographicList bis = new LexicographicList(bi); - LexicographicList bss = new LexicographicList(bs); - assertTrue(m.putIfAbsent(bis, true) == null); - assertTrue(m.containsKey(bis)); - if (m.putIfAbsent(bss, true) == null) - assertTrue(m.containsKey(bss)); - assertTrue(m.containsKey(bis)); - } - for (int i = 0; i < 1000; i++) { - assertTrue(m.containsKey(new ArrayList(Collections.singleton(new BI(i))))); + try (ChronicleMap map = map5()) { + assertTrue(map.containsValue("A")); + assertFalse(map.containsValue("Z")); } } -*/ /** - * Elements of non-comparable classes equal to those of classes - * with erased generic type parameters based on Comparable can be - * inserted and found. + * get returns the correct element at the given key, or null if not present */ - /* @Test public void testGenericComparable2() throws IOException { - ChronicleMap m = - newShmListBoolean(); - for (int i = 0; i < 1000; i++) { - m.put(new ArrayList(Collections.singleton(new BI(i))), true); - } - - for (int i = 0; i < 1000; i++) { - LexicographicList bis = new LexicographicList(new BI(i)); - assertTrue(m.containsKey(bis)); - } - } -*/ - - /** - * get returns the correct element at the given key, - * or null if not present - */ - @Test + @Test(timeout = 5000) public void testGet() throws IOException { - ChronicleMap map = map5(); - assertEquals("A", (String) map.get(one)); - ChronicleMap empty = newShmIntString(); - assertNull(map.get(notPresent)); + try (ChronicleMap map = map5()) { + assertEquals("A", (String) map.get(one)); + try (ChronicleMap empty = newStrStrMap(8078)) { + assertNull(map.get(notPresent)); + } + } } + + /** * isEmpty is true of empty map and false for non-empty */ - @Test + @Test(timeout = 5000) public void testIsEmpty() throws IOException { - ChronicleMap empty = newShmIntString(); - ChronicleMap map = map5(); - assertTrue(empty.isEmpty()); - assertFalse(map.isEmpty()); + try (ChronicleMap empty = newShmIntString(8078)) { + try (ChronicleMap map = map5()) { + + if (!empty.isEmpty()) { + System.out.print("not empty " + empty); + } + assertTrue(empty.isEmpty()); + assertFalse(map.isEmpty()); + } + } } /** * keySet returns a Set containing all the keys */ - @Test + @Test(timeout = 5000) public void testKeySet() throws IOException { - ChronicleMap map = map5(); - Set s = map.keySet(); - assertEquals(5, s.size()); - assertTrue(s.contains(one)); - assertTrue(s.contains(two)); - assertTrue(s.contains(three)); - assertTrue(s.contains(four)); - assertTrue(s.contains(five)); + try (ChronicleMap map = map5()) { + Set s = map.keySet(); + assertEquals(5, s.size()); + assertTrue(s.contains(one)); + assertTrue(s.contains(two)); + assertTrue(s.contains(three)); + assertTrue(s.contains(four)); + assertTrue(s.contains(five)); + } } /** * keySet.toArray returns contains all keys */ - @Test + @Test(timeout = 5000) public void testKeySetToArray() throws IOException { - ChronicleMap map = map5(); - Set s = map.keySet(); - Object[] ar = s.toArray(); - assertTrue(s.containsAll(Arrays.asList(ar))); - assertEquals(5, ar.length); - ar[0] = m10; - assertFalse(s.containsAll(Arrays.asList(ar))); + try (ChronicleMap map = map5()) { + Set s = map.keySet(); + Object[] ar = s.toArray(); + assertTrue(s.containsAll(Arrays.asList(ar))); + assertEquals(5, ar.length); + ar[0] = m10; + assertFalse(s.containsAll(Arrays.asList(ar))); + } } /** * Values.toArray contains all values */ - @Test + @Test(timeout = 5000) public void testValuesToArray() throws IOException { - ChronicleMap map = map5(); - Collection v = map.values(); - Object[] ar = v.toArray(); - ArrayList s = new ArrayList(Arrays.asList(ar)); - assertEquals(5, ar.length); - assertTrue(s.contains("A")); - assertTrue(s.contains("B")); - assertTrue(s.contains("C")); - assertTrue(s.contains("D")); - assertTrue(s.contains("E")); - } + try (ChronicleMap map = map5()) { + Collection v = map.values(); + Object[] ar = v.toArray(); + ArrayList s = new ArrayList(Arrays.asList(ar)); + assertEquals(5, ar.length); + assertTrue(s.contains("A")); + assertTrue(s.contains("B")); + assertTrue(s.contains("C")); + assertTrue(s.contains("D")); + assertTrue(s.contains("E")); - /** - * TODO : enumeration returns an enumeration containing the correct - * elements - */ - /* @Test public void testEnumeration() throws IOException { - ChronicleMap map = map5(); - Enumeration e = map.elements(); - int count = 0; - while (e.hasMoreElements()) { - count++; - e.nextElement(); } - assertEquals(5, count); - }*/ + } /** * entrySet.toArray contains all entries */ - @Test + @Test(timeout = 5000) public void testEntrySetToArray() throws IOException { - ChronicleMap map = map5(); - Set s = map.entrySet(); - Object[] ar = s.toArray(); - assertEquals(5, ar.length); - for (int i = 0; i < 5; ++i) { - assertTrue(map.containsKey(((Map.Entry) (ar[i])).getKey())); - assertTrue(map.containsValue(((Map.Entry) (ar[i])).getValue())); + try (ChronicleMap map = map5()) { + Set s = map.entrySet(); + Object[] ar = s.toArray(); + assertEquals(5, ar.length); + for (int i = 0; i < 5; ++i) { + assertTrue(map.containsKey(((java.util.Map.Entry) (ar[i])).getKey())); + assertTrue(map.containsValue(((java.util.Map.Entry) (ar[i])).getValue())); + } + } } /** * values collection contains all values */ - @Test + @Test(timeout = 5000) public void testValues() throws IOException { - ChronicleMap map = map5(); - Collection s = map.values(); - assertEquals(5, s.size()); - assertTrue(s.contains("A")); - assertTrue(s.contains("B")); - assertTrue(s.contains("C")); - assertTrue(s.contains("D")); - assertTrue(s.contains("E")); - } - - /** - * TODO : keys returns an enumeration containing all the keys from the map - */ - /* @Test public void testKeys() throws IOException { - ChronicleMap map = map5(); - Enumeration e = map.keys(); - int count = 0; - while (e.hasMoreElements()) { - count++; - e.nextElement(); + try (ChronicleMap map = map5()) { + Collection s = map.values(); + assertEquals(5, s.size()); + assertTrue(s.contains("A")); + assertTrue(s.contains("B")); + assertTrue(s.contains("C")); + assertTrue(s.contains("D")); + assertTrue(s.contains("E")); } - assertEquals(5, count); - }*/ + } /** * entrySet contains all pairs */ - @Test + @Test(timeout = 5000) public void testEntrySet() throws IOException { - ChronicleMap map = map5(); - Set s = map.entrySet(); - assertEquals(5, s.size()); - Iterator it = s.iterator(); - while (it.hasNext()) { - Map.Entry e = (Map.Entry) it.next(); - assertTrue( - (e.getKey().equals(one) && e.getValue().equals("A")) || - (e.getKey().equals(two) && e.getValue().equals("B")) || - (e.getKey().equals(three) && e.getValue().equals("C")) || - (e.getKey().equals(four) && e.getValue().equals("D")) || - (e.getKey().equals(five) && e.getValue().equals("E")) - ); + try (ChronicleMap map = map5()) { + Set s = map.entrySet(); + assertEquals(5, s.size()); + Iterator it = s.iterator(); + while (it.hasNext()) { + java.util.Map.Entry e = (java.util.Map.Entry) it.next(); + assertTrue( + (e.getKey().equals(one) && e.getValue().equals("A")) || + (e.getKey().equals(two) && e.getValue().equals("B")) || + (e.getKey().equals(three) && e.getValue().equals("C")) || + (e.getKey().equals(four) && e.getValue().equals("D")) || + (e.getKey().equals(five) && e.getValue().equals("E")) + ); + } + } } /** * putAll adds all key-value pairs from the given map */ - @Test + @Test(timeout = 5000) public void testPutAll() throws IOException { - ChronicleMap empty = newShmIntString(); - ChronicleMap map = map5(); - empty.putAll(map); - assertEquals(5, empty.size()); - assertTrue(empty.containsKey(one)); - assertTrue(empty.containsKey(two)); - assertTrue(empty.containsKey(three)); - assertTrue(empty.containsKey(four)); - assertTrue(empty.containsKey(five)); + + try (ChronicleMap empty = newShmIntString(8076)) { + try (ChronicleMap map = map5()) { + empty.putAll(map); + assertEquals(5, empty.size()); + assertTrue(empty.containsKey(one)); + assertTrue(empty.containsKey(two)); + assertTrue(empty.containsKey(three)); + assertTrue(empty.containsKey(four)); + assertTrue(empty.containsKey(five)); + + + } + } } /** * putIfAbsent works when the given key is not present */ - @Test + @Test(timeout = 5000) public void testPutIfAbsent() throws IOException { - ChronicleMap map = map5(); - map.putIfAbsent(six, "Z"); - assertTrue(map.containsKey(six)); + try (ChronicleMap map = map5()) { + map.putIfAbsent(six, "Z"); + assertTrue(map.containsKey(six)); + + } } /** * putIfAbsent does not add the pair if the key is already present */ - @Test + @Test(timeout = 5000) public void testPutIfAbsent2() throws IOException { - ChronicleMap map = map5(); - assertEquals("A", map.putIfAbsent(one, "Z")); + try (ChronicleMap map = map5()) { + assertEquals("A", map.putIfAbsent(one, "Z")); + } } /** * replace fails when the given key is not present */ - @Test + @Test(timeout = 5000) public void testReplace() throws IOException { - ChronicleMap map = map5(); - assertNull(map.replace(six, "Z")); - assertFalse(map.containsKey(six)); + try (ChronicleMap map = map5()) { + assertNull(map.replace(six, "Z")); + assertFalse(map.containsKey(six)); + + } } /** * replace succeeds if the key is already present */ - @Test - public void testReplace2() throws IOException { - ChronicleMap map = map5(); - assertNotNull(map.replace(one, "Z")); - assertEquals("Z", map.get(one)); + @Test(timeout = 5000) + public void testReplace2() throws + IOException { + try (ChronicleMap map = map5()) { + assertNotNull(map.replace(one, "Z")); + assertEquals("Z", map.get(one)); + } } /** * replace value fails when the given key not mapped to expected value */ - @Test - public void testReplaceValue() throws IOException { - ChronicleMap map = map5(); - assertEquals("A", map.get(one)); - assertFalse(map.replace(one, "Z", "Z")); - assertEquals("A", map.get(one)); + @Test(timeout = 5000) + public void testReplaceValue() throws + IOException { + try (ChronicleMap map = map5()) { + assertEquals("A", map.get(one)); + assertFalse(map.replace(one, "Z", "Z")); + assertEquals("A", map.get(one)); + + } } /** * replace value succeeds when the given key mapped to expected value */ - @Test - public void testReplaceValue2() throws IOException { - ChronicleMap map = map5(); - assertEquals("A", map.get(one)); - assertTrue(map.replace(one, "A", "Z")); - assertEquals("Z", map.get(one)); + @Test(timeout = 5000) + public void testReplaceValue2 + () throws IOException { + try (ChronicleMap map = map5()) { + assertEquals("A", map.get(one)); + assertTrue(map.replace(one, "A", "Z")); + assertEquals("Z", map.get(one)); + + } } /** * remove removes the correct key-value pair from the map */ - @Test - public void testRemove() throws IOException { - ChronicleMap map = map5(); - map.remove(five); - assertEquals(4, map.size()); - assertFalse(map.containsKey(five)); + @Test(timeout = 5000) + public void testRemove() throws + IOException { + try (ChronicleMap map = map5()) { + map.remove(five); + assertEquals(4, map.size()); + assertFalse(map.containsKey(five)); + + } } /** * remove(key,value) removes only if pair present */ - @Test - public void testRemove2() throws IOException { - ChronicleMap map = map5(); + @Test(timeout = 5000) + public void testRemove2 + () throws IOException { + /* try( ChronicleMap map = map5(8076)) { map.remove(five, "E"); - assertEquals(4, map.size()); + assertEquals(4, map.size()); assertFalse(map.containsKey(five)); map.remove(four, "A"); assertEquals(4, map.size()); assertTrue(map.containsKey(four)); + */ } /** * size returns the correct values */ - @Test + @Test(timeout = 5000) public void testSize() throws IOException { - ChronicleMap map = map5(); - ChronicleMap empty = newShmIntString(); - assertEquals(0, empty.size()); - assertEquals(5, map.size()); + try (ChronicleMap map = map5()) { + + try (ChronicleMap empty = newShmIntString(8078)) { + assertEquals(0, empty.size()); + assertEquals(5, map.size()); + } + } + } + + /** + * size returns the correct values + */ + @Test(timeout = 10000) + public void testSize2() throws IOException { + try (ChronicleMap map = map5()) { + + try (ChronicleMap empty = newShmIntString(8078)) { + assertEquals(0, empty.size()); + assertEquals(5, map.size()); + } + } + } + + /** + * size returns the correct values + */ + @Test(timeout = 5000) + public void testSize3() throws IOException { + try (ChronicleMap map = map5()) { + + try (ChronicleMap empty = newShmIntString(8078)) { + assertEquals(0, empty.size()); + assertEquals(5, map.size()); + } + } } /** * toString contains toString of elements */ - @Test + @Test(timeout = 5000) public void testToString() throws IOException { - ChronicleMap map = map5(); - String s = map.toString(); - for (int i = 1; i <= 5; ++i) { - assertTrue(s.contains(String.valueOf(i))); + try (ChronicleMap map = map5()) { + String s = map.toString(); + for (int i = 1; i <= 5; ++i) { + assertTrue(s.contains(String.valueOf(i))); + } + } } /** * get(null) throws NPE */ - @Test + @Test(timeout = 5000) public void testGet_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + + try (ChronicleMap c = newShmIntString(8076)) { c.get(null); shouldThrow(); } catch (NullPointerException success) { } + } /** * containsKey(null) throws NPE */ - @Test + @Test(timeout = 5000) public void testContainsKey_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + try (ChronicleMap c = newShmIntString(8076)) { c.containsKey(null); shouldThrow(); } catch (NullPointerException success) { @@ -512,10 +494,9 @@ public class ChronicleMapTest extends JSR166TestCase { /** * put(null,x) throws NPE */ - @Test + @Test(timeout = 5000) public void testPut1_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + try (ChronicleMap c = newShmIntString(8076)) { c.put(null, "whatever"); shouldThrow(); } catch (NullPointerException success) { @@ -525,10 +506,10 @@ public class ChronicleMapTest extends JSR166TestCase { /** * put(x, null) throws NPE */ - @Test - public void testPut2_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + @Test(timeout = 5000) + public void testPut2_NullPointerException + () throws IOException { + try (ChronicleMap c = newShmIntString(8076)) { c.put(notPresent, null); shouldThrow(); } catch (NullPointerException success) { @@ -538,58 +519,24 @@ public class ChronicleMapTest extends JSR166TestCase { /** * putIfAbsent(null, x) throws NPE */ - @Test - public void testPutIfAbsent1_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + @Test(timeout = 5000) + public void testPutIfAbsent1_NullPointerException + () throws IOException { + try (ChronicleMap c = newShmIntString(8076)) { c.putIfAbsent(null, "whatever"); shouldThrow(); } catch (NullPointerException success) { } } - // Exception tests - - /** - * TODO : Cannot create with negative capacity - */ - /* @Test public void testConstructor1() { - try { - newShmIntString(-1, 0, 1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } - }*/ - - /** - * TODO : Cannot create with negative concurrency level - */ - /*@Test public void testConstructor2() { - try { - newShmIntString(1, 0, -1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } - }*/ - - /** - * TODO :Cannot create with only negative capacity - */ - /* @Test public void testConstructor3() { - try { - newShmIntString(-1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } - }*/ /** * replace(null, x) throws NPE */ - @Test - public void testReplace_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + @Test(timeout = 5000) + public void testReplace_NullPointerException + () throws IOException { + try (ChronicleMap c = newShmIntString(8076)) { c.replace(null, "whatever"); shouldThrow(); } catch (NullPointerException success) { @@ -599,49 +546,23 @@ public class ChronicleMapTest extends JSR166TestCase { /** * replace(null, x, y) throws NPE */ - @Test - public void testReplaceValue_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + @Test(timeout = 5000) + public void testReplaceValue_NullPointerException + () throws IOException { + try (ChronicleMap c = newShmIntString(8076)) { c.replace(null, "A", "whatever"); shouldThrow(); } catch (NullPointerException success) { } } - /** - * containsValue(null) throws NPE - */ -/* @Test public void testContainsValue_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); - c.containsValue(null); - shouldThrow(); - } catch (NullPointerException success) { - } - }*/ - - /** - * todo : contains(null) throws NPE - */ -/* - @Test public void testContains_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); - c.contains(null); - shouldThrow(); - } catch (NullPointerException success) { - } - } -*/ /** * putIfAbsent(x, null) throws NPE */ - @Test + @Test(timeout = 5000) public void testPutIfAbsent2_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + try (ChronicleMap c = newShmIntString(8076)) { c.putIfAbsent(notPresent, null); shouldThrow(); } catch (NullPointerException success) { @@ -651,10 +572,9 @@ public class ChronicleMapTest extends JSR166TestCase { /** * replace(x, null) throws NPE */ - @Test + @Test(timeout = 5000) public void testReplace2_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + try (ChronicleMap c = newShmIntString(8076)) { c.replace(notPresent, null); shouldThrow(); } catch (NullPointerException success) { @@ -664,10 +584,10 @@ public class ChronicleMapTest extends JSR166TestCase { /** * replace(x, null, y) throws NPE */ - @Test - public void testReplaceValue2_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + @Test(timeout = 5000) + public void testReplaceValue2_NullPointerException + () throws IOException { + try (ChronicleMap c = newShmIntString(8076)) { c.replace(notPresent, null, "A"); shouldThrow(); } catch (NullPointerException success) { @@ -677,10 +597,9 @@ public class ChronicleMapTest extends JSR166TestCase { /** * replace(x, y, null) throws NPE */ - @Test + @Test(timeout = 5000) public void testReplaceValue3_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); + try (ChronicleMap c = newShmIntString(8076)) { c.replace(notPresent, "A", null); shouldThrow(); } catch (NullPointerException success) { @@ -690,10 +609,9 @@ public class ChronicleMapTest extends JSR166TestCase { /** * remove(null) throws NPE */ - @Test + @Test(timeout = 5000) public void testRemove1_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmStringString(5); + try (ChronicleMap c = newStrStrMap(8076)) { c.put("sadsdf", "asdads"); c.remove(null); shouldThrow(); @@ -704,10 +622,10 @@ public class ChronicleMapTest extends JSR166TestCase { /** * remove(null, x) throws NPE */ - @Test - public void testRemove2_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmStringString(5); + @Test(timeout = 5000) + public void testRemove2_NullPointerException + () throws IOException { + try (ChronicleMap c = newStrStrMap(8086)) { c.put("sadsdf", "asdads"); c.remove(null, "whatever"); shouldThrow(); @@ -718,13 +636,19 @@ public class ChronicleMapTest extends JSR166TestCase { /** * remove(x, null) returns false */ - @Test + @Test(timeout = 5000) public void testRemove3() throws IOException { - ChronicleMap c = newShmStringString(5); - c.put("sadsdf", "asdads"); - assertFalse(c.remove("sadsdf", null)); + + try (ChronicleMap c = newStrStrMap(8076)) { + c.put("sadsdf", "asdads"); + assertFalse(c.remove("sadsdf", null)); + } } + + + + // classes for testing Comparable fallbacks static class BI implements Comparable { private final int value; diff --git a/src/test/java/net/openhft/chronicle/set/ChronicleSetBuilderTest.java b/src/test/java/net/openhft/chronicle/set/ChronicleSetBuilderTest.java index 7bab578b6..e6cb8f365 100644 --- a/src/test/java/net/openhft/chronicle/set/ChronicleSetBuilderTest.java +++ b/src/test/java/net/openhft/chronicle/set/ChronicleSetBuilderTest.java @@ -21,22 +21,20 @@ package net.openhft.chronicle.set; import org.junit.Assert; import org.junit.Test; -import java.util.Set; - public class ChronicleSetBuilderTest { @Test public void test() throws Exception { - Set integers = ChronicleSetBuilder.of(Integer.class).create(); + try (ChronicleSet integers = ChronicleSetBuilder.of(Integer.class).create()) { - for (int i = 0; i < 10; i++) { - integers.add(i); + for (int i = 0; i < 10; i++) { + integers.add(i); + } + + Assert.assertTrue(integers.contains(5)); + Assert.assertEquals(10, integers.size()); } - Assert.assertTrue(integers.contains(5)); - Assert.assertEquals(10, integers.size()); } - - } diff --git a/src/test/java/net/openhft/chronicle/map/Issue3Test.java b/src/test/java/net/openhft/chronicle/set/Issue3Test.java similarity index 68% rename from src/test/java/net/openhft/chronicle/map/Issue3Test.java rename to src/test/java/net/openhft/chronicle/set/Issue3Test.java index c10802ccd..3315c6a78 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue3Test.java +++ b/src/test/java/net/openhft/chronicle/set/Issue3Test.java @@ -16,31 +16,29 @@ * limitations under the License. */ -package net.openhft.chronicle.map; +package net.openhft.chronicle.set; -import net.openhft.chronicle.set.ChronicleSet; -import net.openhft.chronicle.set.ChronicleSetBuilder; import org.junit.Test; import java.io.IOException; import java.util.Random; -import java.util.Set; public class Issue3Test { @Test public void test() throws IOException { - Set set = ChronicleSetBuilder.of(Long.class) + try (ChronicleSet set = ChronicleSetBuilder.of(Long.class) .actualSegments(1) .actualEntriesPerSegment(1000) - .create(); + .create()) { - Random r = new Random(); - for (int i = 0; i < 10; i++) { - for (int j = 0; j < 300; j++) { - set.add(r.nextLong()); + Random r = new Random(); + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 300; j++) { + set.add(r.nextLong()); + } + set.clear(); } - set.clear(); } } } diff --git a/src/test/java/net/openhft/chronicle/set/SetForTCPSocketReplication3wayTest.java b/src/test/java/net/openhft/chronicle/set/SetForTCPSocketReplication3wayTest.java index 5346a9731..2665523e3 100644 --- a/src/test/java/net/openhft/chronicle/set/SetForTCPSocketReplication3wayTest.java +++ b/src/test/java/net/openhft/chronicle/set/SetForTCPSocketReplication3wayTest.java @@ -77,6 +77,7 @@ public class SetForTCPSocketReplication3wayTest { e.printStackTrace(); } } + System.gc(); }